Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Created February 4, 2019 14:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save tannerlinsley/a78598f751ef0d9f9d8d9973e5ec9ff6 to your computer and use it in GitHub Desktop.
Save tannerlinsley/a78598f751ef0d9f9d8d9973e5ec9ff6 to your computer and use it in GitHub Desktop.
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];
}
@sahilrajput03
Copy link

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