Skip to content

Instantly share code, notes, and snippets.

@ifyour
Last active April 20, 2022 14:00
Show Gist options
  • Save ifyour/97163a5535488339d6d739b21382dfec to your computer and use it in GitHub Desktop.
Save ifyour/97163a5535488339d6d739b21382dfec to your computer and use it in GitHub Desktop.
import React from 'react';
export 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] = React.useState(initialValue);
// Bind the actions with the old state and args
const boundActions = React.useMemo( () => {
let some = {}
Object.keys(actions).forEach((actionName) => {
some[actionName] = (...args) => () =>
setState((old) => actions[actionName](old, ...args));
});
some.setState = setState;
return some
},[])
// Memoize the context value to update when the state does
const contextValue = React.useMemo(() => ({state, ...boundActions}), [state,boundActions])
// const contextValue = React.useMemo(() => [state, boundActions], [state]);
// const contextValue = React.useMemo(() => [state, boundActions, setState], [state]);
// Provide the store to children
return <context.Provider value={contextValue}>{children}</context.Provider>;
};
// A hook to help us consume the store
const useStore = () => React.useContext(context);
return [Provider, useStore];
}
// src: https://gist.github.com/tannerlinsley/699aae70417da8e0c11f7fb7876c49b8
// src: https://gist.github.com/tannerlinsley/a78598f751ef0d9f9d8d9973e5ec9ff6
// src: https://gist.github.com/tannerlinsley/d666b1d9974d7277c74b6fd815986164
// src: https://gist.github.com/tannerlinsley/490272e89c9a822eb3819e97dd5759c1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment