Skip to content

Instantly share code, notes, and snippets.

@cliffordp
Last active July 5, 2020 11:37
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 cliffordp/9440ec1e18b95dd03cf554beb287392b to your computer and use it in GitHub Desktop.
Save cliffordp/9440ec1e18b95dd03cf554beb287392b to your computer and use it in GitHub Desktop.
// 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