Skip to content

Instantly share code, notes, and snippets.

@sahilrajput03
Forked from tannerlinsley/makeStore.js
Last active October 22, 2020 14:56
Show Gist options
  • Save sahilrajput03/a50069869540b3afdcef7c05a1165c04 to your computer and use it in GitHub Desktop.
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
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