Skip to content

Instantly share code, notes, and snippets.

@barklund
Created November 18, 2019 22:51
Show Gist options
  • Save barklund/63f0350a78b90e67e0a0ee3361487792 to your computer and use it in GitHub Desktop.
Save barklund/63f0350a78b90e67e0a0ee3361487792 to your computer and use it in GitHub Desktop.
Context service provider pattern
import { MyServiceProvider, useMyService } from './myservice';
function App() {
return (
<MyServiceProvider>
// more services here
</MyServiceProvider>
);
}
export {
useMyService,
};
export default createContext( { state: {}, actions: {}, data: {} } );
import Context from './myservicecontext';
function MyServiceProvider( { children } ) {
// useState, useCallback, useEffect up here create all these states and actions
const value = {
state: {
someState,
anotherState,
},
actions: {
setSomeState,
loadSomething,
},
data: {
META_CONSTANT,
OTHER_CONSTANT,
},
}
return (
<Context.Provider value={ value }>
{ children }
</Context.Provider>
);
}
import { useMyService } from './app';
function OtherComponent() {
const {
state: { someState, anotherState },
actions: { setSomeState, loadSomething },
data: { META_CONSTANT, OTHER_CONSTANT },
} = useMyService();
// render here
}
import Context from './myservicecontext';
function useMyService() {
return useContext( Context );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment