Skip to content

Instantly share code, notes, and snippets.

@finom
Created May 11, 2020 14:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save finom/ef471ab479d931f2d47d23d7b97be7cb to your computer and use it in GitHub Desktop.
Save finom/ef471ab479d931f2d47d23d7b97be7cb to your computer and use it in GitHub Desktop.
[finom/create-state-context] Creates useState-like hook which uses react context
/*
Can be used to achieve useState hook experience with React Context API
1. Create context with some initial state:
const MyContext = createStateContext(0);
2. Wrap your component by the context provider
<MyContext.Provider>
<MyComponent />
</MyContext.Provider>
3. Use it in your components with built-in react useContext hook:
import { useContext } from 'react';
...
const [value, setValue] = useContext(MyContext);
...
setValue(value + 1);
*/
import { useState, createContext, createElement } from 'react';
export default function createStateContext(initialState) {
// eslint-disable-next-line no-console
const TheContext = createContext([initialState, () => console.error('State context is used but not wrapped by its provider')]);
const { Provider } = TheContext;
TheContext.Provider = ({ children }) => createElement(
Provider,
{ value: useState(initialState) },
children,
);
return TheContext;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment