Created
April 6, 2021 19:04
-
-
Save nico-martin/d6cffd55cb66192fa689ed58a24d0d1b to your computer and use it in GitHub Desktop.
A global state with React.Context and React Hooks
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
import React from 'react'; | |
import { MyContextProvider, useMyContext } from './myContext'; | |
const CompOne = () => { | |
const [myState, setMyState] = useMyContext(); | |
return ( | |
<div> | |
<p> | |
CompOne update:{' '} | |
<button onClick={() => setMyState({ ...myState, foo: 'baz' })}> | |
change foo to baz | |
</button> | |
</p> | |
</div> | |
); | |
}; | |
const CompTwo = () => { | |
const [myState] = useMyContext(); | |
return ( | |
<div> | |
<p>Value of foo: {myState.foo}</p> | |
</div> | |
); | |
}; | |
const App = () => { | |
return ( | |
<MyContextProvider> | |
<CompOne /> | |
<CompTwo /> | |
</MyContextProvider> | |
); | |
}; |
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
import React from 'react'; | |
const MyContext = React.createContext([{}, () => {}]); | |
export const MyContextProvider = ({ children }) => { | |
const [myState, setMyState] = React.useState({ | |
hello: 'world', | |
foo: 'bar', | |
}); | |
return ( | |
<MyContext.Provider value={[myState, setMyState]}> | |
{children} | |
</MyContext.Provider> | |
); | |
}; | |
export const useMyContext = () => React.useContext(MyContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment