-
-
Save sahilrajput03/a50069869540b3afdcef7c05a1165c04 to your computer and use it in GitHub Desktop.
makeStore react hook(without immerjs π) #react #hook #hooks #store #React.createContext #useContext #useContext
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
function makeStore({ actions }) { | |
// Make a context for the store | |
const context = React.createContext(); | |
// Make a provider that takes an initialValue | |
const Provider = ({ initialValue = {}, children }) => { | |
// Make a new state instance | |
const [state, setState] = useState(initialValue); | |
// Bind the actions with the old state and args | |
const boundActions = {} | |
Object.keys(actions).forEach(key => { | |
boundActions[key] = (...args) => | |
setState(old => actions\[key\](old, ...args)) | |
}) | |
// Memoize the context value to update when the state does | |
const contextValue = useMemo(() => [state, boundActions], [state]); | |
// Provide the store to children | |
return <context.Provider value={contextValue}>{children}</context.Provider>; | |
}; | |
// A hook to help us consume the store | |
const useStore = () => useContext(context); | |
return [Provider, useStore]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment