Skip to content

Instantly share code, notes, and snippets.

@jimthedev
Last active January 21, 2020 20:29
Show Gist options
  • Save jimthedev/74d451f71975b504f0a223850481c9c2 to your computer and use it in GitHub Desktop.
Save jimthedev/74d451f71975b504f0a223850481c9c2 to your computer and use it in GitHub Desktop.
React StoreProvider, useStore hook
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)
}
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