Created
May 11, 2020 14:08
-
-
Save finom/ef471ab479d931f2d47d23d7b97be7cb to your computer and use it in GitHub Desktop.
[finom/create-state-context] Creates useState-like hook which uses react context
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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