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];
}
@hervispichardo
Copy link

Hi i have the following error:

TypeError: arr[Symbol.iterator] is not a function
    at _iterableToArrayLimit (webpack-internal:///./node_modules/babel-preset-react-app/node_modules/
babel/runtime/helpers/esm/iterableToArrayLimit.js:10:39
    at _slicedToArray (webpack-internal:///./node_modules/babel-preset-react-app/node_modules/
babel/runtime/helpers/esm/slicedToArray.js:10:151
eval
webpack-internal:///./src/store/index.js:53:194
Module../src/store/index.js
http://localhost:3000/static/js/main.chunk.js:117:1
__webpack_require__
http://localhost:3000/static/js/bundle.js:787:30
fn
http://localhost:3000/static/js/bundle.js:150:20
eval
src/index.js:5

I am trying to follow your code, and be paralyzed in this part.

Stay tuned

@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