Created
April 11, 2022 09:43
-
-
Save lejonmanen/fed1d45194164ed29b735df55adca9f8 to your computer and use it in GitHub Desktop.
React Context demo using 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 { createContext, useState, useContext } from 'react' | |
// Create the context in a separate file. Import it to every component that needs it. | |
const CounterContext = createContext(0) | |
const ContextDemo = () => { | |
const [count, setCount] = useState(2) | |
const contextValue = { count, setCount } | |
return ( | |
<div> | |
<h3> Context demo </h3> | |
<CounterContext.Provider value={contextValue}> | |
<ViewChild /> | |
<ViewChild /> | |
<ViewChild /> | |
<ViewChild /> | |
<ViewChild /> | |
<SetChild /> | |
<SetChild /> | |
</CounterContext.Provider> | |
</div> | |
) | |
} | |
// Doesn't matter how deep in the component hierarchy these components are. | |
const ViewChild = () => { | |
const { count } = useContext(CounterContext) | |
return ( | |
<p> The count is {count}. </p> | |
) | |
} | |
const SetChild = () => { | |
const { setCount } = useContext(CounterContext) | |
return ( | |
<p> <button onClick={() => setCount(c => c + 1)}> Increase count </button> </p> | |
) | |
} | |
export default ContextDemo |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment