đ˛ Context
Working with the React Context API
Example of Prop Drilling
function PropDrilling() {
const [count] = useState(0);
return <Child count={count} />
}
function Child({ count }) {
return <GrandChild count={count} />
}
function GrandChild({ count }) {
return <div>{count}</div>
}
Sharing Data with Context
function PropDrilling() {
const [count] = useState(0);
return (
<CountContext.Provider value={count}>
<Child />
</CountContext.Provider>
)
}
function Child() {
return <GrandChild />
}
function GrandChild() {
const count = useContext(CountContext);
return <div>{count}</div>
}
Challenge
Create CountContext
and CountProvider
that uses { count, setCount }
as its values. This will allow the count and setCount function to be passed to any of its {children}
in the tree.
Create 2 components Count
and CountButton
that can each call useContext(CountContext)
to update the count and display the current count value.