Using Context Well: A Distribution Path, Not Secret Global State
Context solves distributing data through the tree – but not the question of who owns the state. If you confuse the two, you build a global store through the back door and cause unnecessary renders when provider values change carelessly.
Using Context Well: A Distribution Path, Not Secret Global State
const AppContext = createContext(null);
function AppProvider({ children }) {
const [user, setUser] = useState(null);
const [filter, setFilter] = useState("");
const [items, setItems] = useState([]);
return (
<AppContext.Provider value={{ user, setUser, filter, setFilter, items, setItems }}>
{children}
</AppContext.Provider>
);
}
Three pieces of state hang off a single provider, and the object behind value is created anew on every render. One character in the filter field is enough, and everything that reads this Context re-renders along with it – including the header, which only shows the name of the signed-in person. A shortcut through the component tree has turned into a store without anyone consciously making that decision.
Context can do exactly one thing: provide a value at the top and make it readable further down, without the layers in between passing it along. Everything else – where the value comes from, who updates it, how often it changes – remains manual work and has to be decided beforehand. Let us start with the problem Context was built for.
The problem: prop drilling#
In React, data flows from top to bottom. A component passes values to its children through props, they pass them on to their children, and so on. As long as the path is short, that is exactly right – the data flow is visible, and you can read from the props what a component needs.
It gets unpleasant when a value is created far up and needed far down, but nothing in between needs it at all. Take the signed-in person: they are determined once at the very top, and needed in the header, in a comment form deep in the tree and in a menu somewhere else entirely. All components along the way have to accept the value and pass it on, even though they only funnel it through.
function Page({ user }) {
return <Layout user={user} />;
}
function Layout({ user }) {
return <Sidebar user={user} />;
}
function Sidebar({ user }) {
return <Profile user={user} />;
}
function Profile({ user }) {
return <span>{user.name}</span>;
}
Layout and Sidebar do not care about user. They only carry the prop along because someone further down needs it. That is exactly what is called prop drilling – you drill a value through a layer of components that have nothing to do with it. It makes intermediate components harder to reuse, because they are coupled to data they only pass through, and every new intermediate layer has to take the prop along by hand.
flowchart TB
subgraph drilling["prop drilling"]
P1["Page (user)"] --> L1["Layout<br/>only passes user on"]
L1 --> S1["Sidebar<br/>only passes user on"]
S1 --> Pr1["Profile<br/>needs user"]
end
subgraph context["Context"]
P2["Provider (user)"] -.-> Pr2["Profile<br/>reads via useContext"]
endHow Context works#
Context reverses this passing along. Instead of handing a value down layer by layer, you provide it once at the top and read it directly at the bottom – without bothering the layers in between. Three parts belong to it: createContext creates the object, a Provider provides the value for a subtree, and useContext reads it where it is needed.
import { createContext, useContext } from "react";
const CurrentUserContext = createContext(null);
function Page({ user }) {
return (
<CurrentUserContext.Provider value={user}>
<Layout />
</CurrentUserContext.Provider>
);
}
function Profile() {
const user = useContext(CurrentUserContext);
return <span>{user.name}</span>;
}
Layout and Sidebar are out of the picture – they no longer know about user and do not have to pass anything on. Profile takes the value directly from the nearest provider above it. That is exactly the job of Context, and for this job it is the right tool: it is a distribution path, a shortcut through the tree.
What matters is what does not happen here. The provider does not create the value. It receives it from above and makes it available. Where user comes from, who changes it, where it lives – all of that is still completely open at this point. And this is exactly where the problems start if you are not careful.
The central trap: Context as a substitute for state ownership#
Because Context makes values so conveniently available everywhere, a temptation is close at hand: you simply put everything in it that several components need. The loaded list, the current filter, half-opened dialogs, the entire application state – Context becomes the storage place for everything shared. That feels great at first and reliably takes its revenge later.
Two consequences come back to bite you. The first is rendering. React compares the old and new provider value with Object.is. If they differ, the components that read this Context re-render; plain descendants without useContext are not automatically affected. With a large object as the Context value, however, a changed reference also affects consumers that only use a different field from it. A small update can turn into a wave of renders this way.
flowchart TB Change["Context value changes"] --> P["Provider"] P --> C1["Consumer A<br/>shows the value"] P --> C2["Consumer B<br/>reads another field –<br/>re-renders anyway"] P --> C3["Consumer C<br/>reads another field –<br/>re-renders anyway"]
In one project, the value of a search field happened to sit in the same Context as the theme. With every keystroke in the search field, half the UI flickered – components that had nothing to do with the search re-rendered along with it, just because they were attached to the same Context. The value had ended up in the wrong container.
The second consequence is coupling. Everything that reads from a Context is bound to that provider. You can no longer use, test or reuse such a component in isolation without building the matching provider around it. The more a Context holds, the more components depend on it, and the more sluggish the application becomes. Context makes the origin of a value invisible – that is an advantage for distribution and a problem for ownership, because you no longer see who is actually responsible for a value.
The core of the misunderstanding is this: Context answers the question “how does the data get to where it is needed.” It does not answer the question “who owns the data and who may change it.” You still have to answer the second question – state ownership – yourself, with useState or useReducer in a clearly named component. Context does not replace this decision; it only transports its result.
Rules for clean use#
Three rules follow from this separation, and they keep Context exactly what it is meant to be – a means of transport.
First: ownership lives at the top, Context only passes it through. The state belongs in a clearly named component – let us call it CurrentUserProvider – that holds it with useState or useReducer. This component is the one place where the value lives and is changed. Context transports it from there downward, nothing more. If you open the provider and look for useState, you find the owner right away; if you do not find it, you have probably built hidden global state.
Second: keep the value stable. This is where the most common concrete mistake lies. If you write a fresh object directly into value, every render of the provider component creates a new reference – and because the reference changes, all consumers re-render, even if nothing has changed in content:
function CurrentUserProvider({ children }) {
const [user, setUser] = useState(null);
// new object on every render → all consumers re-render
return (
<CurrentUserContext.Provider value={{ user, setUser }}>
{children}
</CurrentUserContext.Provider>
);
}
The fix is to memoize the value so that the reference only changes when something has actually changed:
function CurrentUserProvider({ children }) {
const [user, setUser] = useState(null);
const value = useMemo(() => ({ user, setUser }), [user]);
return (
<CurrentUserContext.Provider value={value}>
{children}
</CurrentUserContext.Provider>
);
}
With state from useReducer, a second step is often worth it: put state and dispatch into two separate Contexts. Dispatch is stable; it never changes. If you split it off, components that only trigger actions and do not display the state at all no longer re-render on a state change – they only depend on the immutable dispatch Context.
const StateContext = createContext(null);
const DispatchContext = createContext(null);
function StoreProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<StateContext.Provider value={state}>
<DispatchContext.Provider value={dispatch}>
{children}
</DispatchContext.Provider>
</StateContext.Provider>
);
}
Third: do not put every changing value into it. Some things you reflexively put into a Context belong elsewhere. Server data – loaded lists, detail data, search results – is not application state but a cache, and it belongs in a data fetching library, not in Context. I covered this boundary in detail in “Client State vs. Server Cache.” And the current selection, the filter, the page in a list belong in the URL – shareable, bookmarkable, and they survive a reload. Subtract these two categories and surprisingly little is left for Context, and exactly that remainder is its real home.
What Context is really good for#
Context plays to its strength with rarely changing, app-wide things – with what describes the environment of an application rather than its actual data. The active theme, the selected language, the signed-in person, an app-wide service or dispatch function: such values change rarely but are needed in many places. That is exactly what a distribution path that skips the layers in between is meant for.
The common denominator of these good cases is that they are “environment” and not “application data.” They do not change every second, so the wave of renders hardly matters. And they really are app-wide, so the coupling to a provider does not get in the way – you only want to use these components inside the application anyway. Before every new Context, a test question is therefore worth asking: does the value describe the environment a component runs in, or the data it displays? Only the former belongs in it.
Context and reducer as a small global core#
For a manageable global core, Context and useReducer can be combined into a lightweight pattern. The reducer holds the state and the logic in one place, two separate Contexts distribute state and dispatch, and consumers access them through small hooks:
function useStore() {
return useContext(StateContext);
}
function useDispatch() {
return useContext(DispatchContext);
}
That goes surprisingly far – for a shopping cart, a few app-wide settings, a small set of actions. Ownership is clear (in the StoreProvider), transport is clean (two Contexts), and separating state and dispatch keeps renders in check.
But you should know the limit of this pattern and name it openly: Context is not state management, it is transport. The reducer next to it is the actual logic, and Context only passes its result through. As long as the core stays small, the pattern holds. When the logic grows – many interdependent pieces of state, selectively reading individual fields without waves of renders, middleware, persistence, time travel while debugging – the combination reaches its limits. Then you need a real store that is built for exactly these jobs. That is not a defeat for Context, but the right division of labor: Context never claimed to be a store.
What should stick#
Context answers a single question very well: how the data gets to where it is needed. It does not answer the other, more important question: who owns it and who changes it. You have to answer that second question yourself, in a clearly named component with useState or useReducer, before you touch Context at all.
If you keep these two questions cleanly apart, you use Context for what it is – a distribution path for a few rarely changing, app-wide values, with a stable value and, where needed, separate state and dispatch Contexts. If you mix them up, you build global state through the back door, complete with waves of renders and coupling. The difference costs one single deliberate decision while writing and saves a lot of debugging afterwards.
Further reading#
- Repository introduction-react: https://github.com/mikebild/introduction-react
- react.dev, “Passing Data Deeply with Context”: https://react.dev/learn/passing-data-deeply-with-context
- react.dev, “Scaling Up with Reducer and Context”: https://react.dev/learn/scaling-up-with-reducer-and-context
- react.dev:
useContext, value comparison and re-rendering
Revised and translated from German with the help of AI.