Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
// By Tanner Linsley 2020-07-01
// 5min walk-through: https://share.getcloudapp.com/OAuBjlZW
const globalStateContext = React.createContext()
const useGlobalState = () => React.useContext(globalStateContext)
function App() {
const [globalState, setGlobalState] = React.useState({
foo: 'bar',
})
const globalStateContextValue = React.useMemo(
() => [globalState, setGlobalState],
[globalState]
)
return (
<globalStateContext.Provider value={globalStateContextValue}>
<LevelOne />
</globalStateContext.Provider>
)
}
function LevelOne() {
return <LevelTwo />
}
function LevelTwo() {
return <LevelThree />
}
function LevelLevel() {
const [{ foo }, setGlobalState] = useGlobalState()
setGlobalState((old) => {
return {
...old,
foo: 'baz',
}
})``
return <div>Foo: {globalState.foo}</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.