Sub topic 7
Sharing Changing State Through Context
This chapter assumes you can write function components with JSX and props, and that you have used useState. You should also know that a component re-renders when its state or props change. You have already seen createContext, Provider and useContext. Here you will use them to share values that change over time.
Context carries a value, not state
Context has no state of its own. A provider hands a value to the components below it, and nothing more. If that value never changes, such as a fixed configuration object, the provider is all you need.
To share something that changes, such as a theme, a cart or the signed-in user, you keep the state in an ordinary component with useState. That component renders a provider and passes the current state as the provider's value. When the state changes, the component re-renders and the provider receives a new value. React then updates every component below it that reads the context.
This gives you one rule to remember:
- State lives in a component, and that component is usually the one that renders the provider.
- Context is only the delivery route from that component to its descendants.
The basic pattern
The example below shares a shopping cart. The header shows the number of items. A button deep in the tree adds one. Neither component receives props from App.
import { createContext, useContext, useState } from 'react';
const CartContext = createContext({ items: [], setItems: () => {} });
export default function App() {
const [items, setItems] = useState([]);
return (
<CartContext.Provider value={{ items, setItems }}>
<Header />
<ProductList />
</CartContext.Provider>
);
}
function Header() {
const { items } = useContext(CartContext);
return <h1>Cart ({items.length})</h1>;
}
function ProductList() {
return (
<ul>
<li>
Tea <AddButton name="Tea" />
</li>
<li>
Coffee <AddButton name="Coffee" />
</li>
</ul>
);
}
function AddButton({ name }) {
const { setItems } = useContext(CartContext);
return (
<button onClick={() => setItems((prev) => [...prev, name])}>
Add
</button>
);
}Follow what happens when a user clicks "Add":
AddButtoncallssetItems, which is the setter returned byuseStateinApp.- React schedules a re-render of
Appwith the newitemsarray. Apprenders the provider with a newvalueobject.- React finds every component that called
useContext(CartContext)below that provider and re-renders it.Headernow shows the new count.
The state flows down through context. Updates flow up because the setter is passed down through the same context. AddButton never needs to know which component owns the state.
What belongs in the value
A provider can pass any value, so you choose what consumers can do. There are three common shapes.
| Shape | Example `value` | Consumers can |
|---|---|---|
| State only | `items` | Read, not change |
| State and raw setter | `{ items, setItems }` | Read and replace freely |
| State and named actions | `{ items, addItem, clear }` | Read and change only through the actions you define |
Passing the raw setter is the quickest option, and it is fine in small apps. Named actions are safer in larger ones. Consumers cannot put the state into a shape you did not plan for, and you can change how the state is stored without editing every consumer. Later chapters show how to package actions in a custom provider and a custom hook.
Where the provider sits decides the state's lifetime
The state belongs to the component that calls useState, so the position of that component controls how long the state lasts and who shares it.
- If
Appowns the state and the provider wraps the whole app, the state lasts as long as the app does. Every consumer sees the same value. - If a
ProductPagecomponent owns the state, the state is created whenProductPagemounts. It is discarded whenProductPageunmounts. Components outsideProductPagecannot read it. - If you render the same stateful provider component twice, each copy has its own independent state. Two sidebars that each wrap their own
ThemeProviderdo not stay in sync.
Put the provider as low as possible while still covering every consumer. A provider placed too high keeps state alive longer than needed. It also makes more components eligible to re-render when the value changes.
Reading and updating correctly
Context does not change how state updates work, so the usual rules for useState still apply.
Do not mutate the state. This update looks plausible but is wrong:
// Wrong: mutates the existing array, then sets the same reference
setItems((prev) => {
prev.push(name);
return prev;
});React compares the old and new state with Object.is. Because prev and the returned array are the same object, React sees no change and may skip the re-render. Create a new array instead, as AddButton does with [...prev, name].
Use the functional form when the new state depends on the old. setItems((prev) => [...prev, name]) is correct even when two clicks are batched into one render. Writing setItems([...items, name]) inside a consumer reads items from the render in which the handler was created, so a stale value can overwrite a recent update.
Remember that a consumer only sees the nearest provider. useContext reads from the closest matching provider above the component. If there is none, it returns the default value from createContext. In the example above the default is { items: [], setItems: () => {} }. A consumer rendered outside App would show an empty cart, and its setItems would do nothing. React reports no error, which makes a missing provider easy to overlook.
Which components re-render
When the provider's value changes, React re-renders every component that reads that context, wherever it sits in the tree. Components that do not call useContext for it are not re-rendered because of the context change.
The check is made with Object.is(oldValue, newValue). This matters for the cart example, because value={{ items, setItems }} builds a new object on every render of App. Any time App re-renders for any reason, such as its own parent updating, every consumer of CartContext re-renders too, even if items is the same array. For a small tree this cost is negligible. It becomes a problem when the value is large, when updates are frequent, or when consumers are expensive to render. The next chapters cover how re-renders are triggered and how to limit them. For now, remember that the value's identity is what React compares, not its contents.
A second example: a signed-in user
The same pattern works with any state type. Here the state is a nullable user object, and the value is a pair of state and a function:
import { createContext, useContext, useState } from 'react';
const UserContext = createContext({ user: null, setUser: () => {} });
export default function App() {
const [user, setUser] = useState(null);
return (
<UserContext.Provider value={{ user, setUser }}>
<Greeting />
<AuthButton />
</UserContext.Provider>
);
}
function Greeting() {
const { user } = useContext(UserContext);
return <p>{user ? `Hello, ${user.name}` : 'Please sign in'}</p>;
}
function AuthButton() {
const { user, setUser } = useContext(UserContext);
return user ? (
<button onClick={() => setUser(null)}>Sign out</button>
) : (
<button onClick={() => setUser({ name: 'Sam' })}>Sign in</button>
);
}AuthButton both reads and writes the context. It re-renders after every change, so its label always matches the state. Greeting only reads.
Common mistakes
- Forgetting
value.<CartContext.Provider>with novalueprop gives consumersundefined, not the default. - Calling
useStateinside the consumer. That creates private state in each component. Two components that both do this never share anything. - Expecting the provider to remember state. If the component that owns the state unmounts, the state is gone, even though the context object still exists.
- Putting everything in one context. An unrelated update, such as a modal opening, then re-renders every consumer of the shared context. Group values by how they change, as the later chapter on splitting contexts describes.
Exercise
In the cart example, App owns the state and passes { items, setItems } through CartContext.Provider. A teammate moves the useState call from App into ProductList and keeps the provider in App, so the provider's value is { items, setItems } built from variables that no longer exist in App. They then fix it by adding a second useState in Header for its own items. Why does the header count never change when the user clicks "Add", and where should the state live instead?
Show answer
Each useState call creates separate state owned by the component that calls it. The items in Header is private to Header, and AddButton updates a different state, so the two are never connected. Context only delivers a value that the provider's component passes down. The state must live in the component that renders the provider (here App), or in a component above all consumers. Consumers should then read items and call setItems from useContext(CartContext) rather than creating their own state.
Exercise
Write the line that adds an item to the cart so that two quick clicks in the same event batch both appear in the array. Then say what goes wrong with setItems([...items, name]).
Show answer
Use setItems((prev) => [...prev, name]). The functional form receives the latest pending state each time it runs, so both additions are kept. With setItems([...items, name]), items is the value from the render in which the handler was created. Two calls in one batch both start from that same array, so the second overwrites the first and one item is lost.