Created
August 3, 2020 16:11
-
-
Save tannerlinsley/6140e91b77c5b170471b0686b0872754 to your computer and use it in GitHub Desktop.
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 React from 'react' | |
import immer from 'immer' | |
// | |
export default function makeStore() { | |
// Create a context for this store | |
const context = React.createContext() | |
let store = {} | |
const Provider = ({ children, initialState = {} }) => { | |
const [state, preSetState] = React.useState(() => initialState) | |
const setState = React.useCallback( | |
updater => | |
preSetState(old => { | |
const newState = immer(old, draft => updater(draft)) | |
return newState | |
}), | |
[preSetState] | |
) | |
store.state = state | |
const contextValue = React.useMemo(() => [state, setState], [ | |
setState, | |
state, | |
]) | |
return <context.Provider value={contextValue}>{children}</context.Provider> | |
} | |
const useStore = () => React.useContext(context) | |
store.Provider = Provider | |
store.useStore = useStore | |
return store | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment