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