Last active
April 12, 2023 12:33
-
-
Save lejonmanen/b3753bd1b71837222cb42acdd1c94b6d to your computer and use it in GitHub Desktop.
React context example
This file contains hidden or 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 { useState } from 'react' | |
import { CounterContext } from './CounterContext.js' | |
/* The ancestor is the component that owns this particular piece of data. The ancestor is the only component that knows how to modify it. Therefore, if the descendants should be able to modify the value, we must send the set function as well. | |
If the descendants only need to read the value, we replace the object "countPackage" with the value "count". | |
*/ | |
const Ancestor = () => { | |
// Initialize using default data | |
const [count, setCount] = useState(10) | |
const countPackage = { count, setCount } | |
// The Provider gives all descendants inside access to the value. | |
return ( | |
<CounterContext.Provider value={countPackage}> | |
<Descendant /> | |
</CounterContext.Provider> | |
) | |
} | |
export default Ancestor |
This file contains hidden or 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 } from 'react' | |
// The default data is used if you forget to provide a value when using the Provider | |
const initialData = { value: 0, setValue: () => {} } | |
export const UserContext = createContext(initialData) |
This file contains hidden or 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 { useContext } from 'react' | |
import { CounterContext } from './CounterContext.js' | |
const Descendant = () => { | |
const { count, setCount } = useContext(CounterContext) | |
// If you only need the value write: const { count } = ... | |
// If you only need the set function: const { , setCount } = ... | |
const handleClick = () => setCount(c => c + 1) | |
return ( | |
<> | |
<p> Count is: {count} </p> | |
<button onClick={handleClick}> +1 </button> | |
</> | |
) | |
} | |
export default Descendant |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment