Last active
January 21, 2020 20:29
-
-
Save jimthedev/74d451f71975b504f0a223850481c9c2 to your computer and use it in GitHub Desktop.
React StoreProvider, useStore hook
This file contains 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
const context = React.createContext() | |
export const StoreProvider = ({ children, initialState = {} }) => { | |
const [store, setStore] = React.useState(() => initialState) | |
const contextValue = React.useMemo(() => [store, setStore], [store]) | |
return ( | |
<context.Provider value={contextValue}> | |
{children} | |
</context.Provider> | |
) | |
} | |
export default function useStore() { | |
return React.useContext(context) | |
} |
This file contains 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 immer from 'immer' | |
export const StoreProvider = ({ children, initialState = {} }) => { | |
const [store, setStore] = React.useState(() => initialState) | |
const immerSetStore = React.useCallback( | |
updater => setStore(old => immer(old, draft => updater(draft))), | |
[setStore] | |
) | |
const contextValue = React.useMemo(() => [store, immerSetStore], [ | |
setState, | |
store, | |
]) | |
return <context.Provider value={contextValue}>{children}</context.Provider> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment