Created
November 18, 2019 22:51
-
-
Save barklund/63f0350a78b90e67e0a0ee3361487792 to your computer and use it in GitHub Desktop.
Context service provider pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { MyServiceProvider, useMyService } from './myservice'; | |
function App() { | |
return ( | |
<MyServiceProvider> | |
// more services here | |
</MyServiceProvider> | |
); | |
} | |
export { | |
useMyService, | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default createContext( { state: {}, actions: {}, data: {} } ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> | |
); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useMyService } from './app'; | |
function OtherComponent() { | |
const { | |
state: { someState, anotherState }, | |
actions: { setSomeState, loadSomething }, | |
data: { META_CONSTANT, OTHER_CONSTANT }, | |
} = useMyService(); | |
// render here | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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