Skip to content

Instantly share code, notes, and snippets.

@lejonmanen
Last active April 12, 2023 12:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lejonmanen/b3753bd1b71837222cb42acdd1c94b6d to your computer and use it in GitHub Desktop.
Save lejonmanen/b3753bd1b71837222cb42acdd1c94b6d to your computer and use it in GitHub Desktop.
React context example
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
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)
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