Skip to content

Instantly share code, notes, and snippets.

@tannerlinsley
Last active February 8, 2019 16:27
Show Gist options
  • Save tannerlinsley/5bf5e6adb9ac4a0ddeeaa2003d7f831c to your computer and use it in GitHub Desktop.
Save tannerlinsley/5bf5e6adb9ac4a0ddeeaa2003d7f831c to your computer and use it in GitHub Desktop.
function makeStore() {
// 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 (could even use immer here!)
const [state, setState] = useState(initialValue);
// Memoize the context value to update when the state does
const contextValue = useMemo(() => [state, setState], [state]);
// Provide the store to children
return <context.Provider value={contextValue}>{children}</context.Provider>;
};
// A hook to help consume the store
const useStore = () => useContext(context);
return { Provider, useStore };
}
@ditransler
Copy link

Hello, Tanner,

Shouldn't it be square brackets (return [ Provider, useStore ];) on the line 20 instead of curly ones as you destructure an array const [StoreProvider, useStore] = makeStore(); in the store.js ?

@tannerlinsley
Copy link
Author

yes it should!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment