Created
January 19, 2021 12:11
-
-
Save kcoyner/f7303c0a56b7fc2e9b32d76ea7d97035 to your computer and use it in GitHub Desktop.
example of useContext
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, { useState } from 'react'; | |
// Create a Context | |
const MyContext = React.createContext(); | |
// It returns an object with 2 values: { Provider, Consumer } | |
function ParentComponent() { | |
const [counter, setCounter] = useState(0); | |
// Create an object containing both the value and the setter | |
const contextValue = {counter, setCounter}; | |
return ( | |
<MyContext.Provider value={contextValue}> | |
<SomeChildComponent /> | |
</MyContext.Provider> | |
) | |
} | |
// ---------- some other page --------- // | |
import React, { useContext } from 'react'; | |
function NestedChildComponent() { | |
const { counter, setCounter } = useContext(MyContext); | |
// do something with the counter value and setter | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment