Sub topic 7
Sharing changing state through context
This chapter assumes you know createContext, Provider and useContext from the earlier chapters. It also assumes you are comfortable with useState. Here you will make a context carry a value that changes over time.
Why context alone is not state
Context does not store anything. It is a channel that delivers whatever value the nearest Provider receives. If that value never changes, the context is a constant. To share state that changes, you keep the state in a component with useState and pass the current value into the Provider.
The pattern has three steps:
- Call
useStatein the component that renders the Provider. - Pass the state value, and usually the function that updates it, as the Provider's
value. - Call
useContextin any descendant that needs to read or change the state.
A worked example: a shared counter
This example shares a cart count between a header badge and a product button. Neither component receives props.
import { createContext, useContext, useState } from 'react';
const CartContext = createContext(null);
function CartProvider({ children }) {
const [count, setCount] = useState(0);
return (
<CartContext.Provider value={{ count, setCount }}>
{children}
</CartContext.Provider>
);
}
function CartBadge() {
const { count } = useContext(CartContext);
return <span>Cart: {count}</span>;
}
function AddButton() {
const { setCount } = useContext(CartContext);
return <button onClick={() => setCount((c) => c + 1)}>Add to cart</button>;
}
function Header() {
return (
<header>
<CartBadge />
</header>
);
}
export default function App() {
return (
<CartProvider>
<Header />
<main>
<AddButton />
</main>
</CartProvider>
);
}CartBadge and AddButton sit in different branches of the tree. Both read the same Provider, so they share one piece of state.
What happens when you click
The sequence below shows how a click reaches the badge.
The state belongs to CartProvider, not to the consumers. A consumer can only change it by calling the setter that the Provider exposed. This keeps one source of truth.
Using the updater form
AddButton calls setCount((c) => c + 1) instead of setCount(count + 1). The updater form lets the button depend only on setCount. It does not need to read count, so you can later give the setter to components that never see the value.
Common mistakes
- Putting the Provider too low. Only components below the Provider can read the state. If
Headerrendered outsideCartProvider,useContextwould return the default value, which isnullhere. Destructuringnullthen throws an error. - Mutating state directly. Writing
count++or pushing into an array does not trigger a re-render. Always call the setter with a new value. - Putting everything in one context. A single context for the whole app makes every consumer depend on every change. Later chapters cover how to limit this.
Where to keep the state
Place the state in the lowest component that contains every consumer. For app-wide data such as a logged-in user, that is usually near the root. For a feature such as a multi-step form, wrap only that feature. A narrow Provider limits how many components can be affected by an update.
Exercise
In the counter example, you move <AddButton /> outside <CartProvider> and render it as a sibling of the Provider. What happens when it renders and when it is clicked, and how do you fix it?
Show answer
useContext(CartContext) finds no Provider above the component, so it returns the default value null. Destructuring { setCount } from null throws a TypeError as soon as AddButton renders. The fix is to render AddButton inside CartProvider, for example by wrapping both Header and AddButton in it.