Created
February 4, 2019 14:59
-
-
Save tannerlinsley/a78598f751ef0d9f9d8d9973e5ec9ff6 to your computer and use it in GitHub Desktop.
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]; | |
} |
https://codesandbox.io/s/makestore-react-context-easiest-solution-4hiu4?file=/src/App.js
It works great!!!
Thanks Tanner Linsley, its great to use this hook nowonwards, I feel that are go awesome with hook even before 2 years, its just awesome!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi i have the following error:
I am trying to follow your code, and be paralyzed in this part.
Stay tuned