Sub topic 13
When context is the wrong tool
This chapter assumes you can build a provider and read it with useContext, and that you know why a state change re-renders a component and its children. Context is easy to reach for, so this chapter covers the cases where something else fits better. The alternatives are plain props, component composition, a server-state library, and an external store.
Context is a delivery mechanism, not a state manager
Context moves a value from a provider to any descendant that asks for it. It does not store state, derive values, batch updates, or let a consumer pick one piece of the value. State still lives in useState or useReducer inside the provider. Context only avoids passing that state through every layer in between.
Most of the trouble comes from expecting more than that. Teams adopt context as a global store, then hit re-render problems, hidden dependencies, and code that is hard to reuse. Each problem below shows the symptom, why it happens, and what to use instead.
Case 1: the tree is shallow
Passing a prop through one or two layers is not prop drilling. It is explicit, and it is the cheapest form of data flow to read. When you open <ProfileCard user={user} />, you can see its inputs without leaving the file.
Context makes those inputs invisible. A component that calls useContext(UserContext) works only if some ancestor provides the right value. That affects:
- Reuse. The component can't be dropped into another tree without recreating the provider.
- Testing. Every test must wrap the component in a provider, or the component falls back to the default value.
- Reading. You can't tell from the parent what a child depends on.
Use props until the passing is genuinely painful, meaning many layers where the middle components never use the value.
Case 2: composition would remove the drilling
Prop drilling is often a sign that components are shaped wrongly, not that context is missing. If a middle component receives a prop only to forward it, you can often build the child element higher up and pass it down as children or a named slot prop.
function Page({ user }) {
return (
<Layout
header={<Header avatar={<Avatar user={user} />} />}
content={<Feed />}
/>
);
}
function Layout({ header, content }) {
return (
<div>
<header>{header}</header>
<main>{content}</main>
</div>
);
}
function Header({ avatar }) {
return <nav>{avatar}</nav>;
}
function Avatar({ user }) {
return <img src={user.avatarUrl} alt={user.name} />;
}
function Feed() {
return <p>Feed</p>;
}Layout and Header never see user. Page creates <Avatar user={user} /> itself and hands the finished element down. This is called inversion of control: the component that owns the data decides what to render, and intermediate components only provide places to put it.
The limit is that composition puts more logic in the top component. If many unrelated components deep in the tree need the same value, such as the current theme or locale, context is the better fit. Try composition first when only one or two components need the data.
Case 3: the value changes often
When a provider's value changes, React re-renders every component that calls useContext for that context. It does not matter whether the component uses the part that changed. A consumer cannot subscribe to a single field.
import { createContext, useContext, useMemo, useState } from 'react';
const AppContext = createContext(null);
export function AppProvider({ children }) {
const [theme] = useState('dark');
const [cursor, setCursor] = useState({ x: 0, y: 0 });
const value = useMemo(() => ({ theme, cursor, setCursor }), [theme, cursor]);
return (
<AppContext.Provider value={value}>
<div onMouseMove={(e) => setCursor({ x: e.clientX, y: e.clientY })}>
{children}
</div>
</AppContext.Provider>
);
}
export function ThemeBadge() {
const { theme } = useContext(AppContext);
console.log('ThemeBadge rendered');
return <span>{theme}</span>;
}ThemeBadge reads only theme, but it re-renders on every mouse move, because cursor is part of the same object and the object changes each time. Memoizing the value does not help here, since the contents really did change.
You have three options:
- Split the contexts, so fast-changing and slow-changing data live apart (covered in an earlier chapter). This works when the groups are clear.
- Keep fast data local. Pointer position, text input, and animation values rarely need to be shared. Keep them in the component that uses them.
- Move to a store with selectors (see below), which lets a component subscribe to one slice.
Context suits values that change rarely and are read widely: theme, locale, current user, feature flags. It suits values that change many times per second poorly.
Case 4: the data comes from a server
Server data is a common misuse of context. A provider calls fetch in an effect, stores the result in state, and shares it. That works on day one. You then need to add:
- Loading and error states for each request.
- Caching, so two components don't fetch the same URL.
- Refetching when the window regains focus or the data goes stale.
- Cancelling or ignoring out-of-order responses.
- Invalidating data after a mutation.
You end up rebuilding a data-fetching library inside a provider, and every consumer re-renders when any piece of that state changes. Libraries such as TanStack Query and SWR do this work already, and they let components subscribe per query key. Frameworks with built-in data loading, such as Next.js or React Router, handle it at the route level.
Context still has a role here. You might provide a configured API client or a query client through context, since that object rarely changes.
Case 5: many components share fast-moving, structured state
When a large part of the app reads and writes the same state (a shopping cart, an editor document, a dashboard of filters), an external store usually works better. It keeps state outside React and lets components subscribe to the slice they need. A component re-renders only if its selected value changes.
import { create } from 'zustand';
const useCartStore = create((set) => ({
items: [],
add: (item) => set((state) => ({ items: [...state.items, item] })),
}));
function CartCount() {
const count = useCartStore((state) => state.items.length);
return <span>Cart: {count}</span>;
}
function AddButton() {
const add = useCartStore((state) => state.add);
return <button onClick={() => add({ id: Date.now() })}>Add item</button>;
}AddButton selects only the add function, which never changes, so it never re-renders when the cart changes. No provider is needed either. Redux Toolkit, Jotai, and Zustand all follow this model. They are built on React's useSyncExternalStore hook, which you can use directly for a small custom store.
The cost is a new dependency and another place where state lives. Add it when you can name the problem it solves, such as measured re-render cost or state that must be read outside components.
Comparing the options
| Situation | Better choice |
|---|---|
| Value used by one or two nearby components | Props |
| Middle components only forward a prop | Composition with `children` or slot props |
| Rarely changing value read by many components | Context |
| Frequently changing value read by a few components | Local state, or lifted state |
| Data fetched from an API | TanStack Query, SWR, or framework data loading |
| Large shared state with many readers and writers | External store with selectors |
A decision path
Treat this as a starting point. A cart that changes only on button clicks may work fine in context, while a theme toggled thousands of times in a test harness may not.
Two other warning signs
A single giant context. If one AppContext holds user, theme, cart, notifications, and modal state, every consumer re-renders when any of them changes. It is also hard to tell which component depends on what. Prefer several small contexts, each with one concern.
Context used to avoid designing data flow. If you notice you can't explain where a value comes from or who may change it, the problem is structure, and a provider will not fix it. Write down which component owns the state, then check whether that component can sit closer to its consumers.
Checking your choice
A quick test before you write createContext:
- Can I name at least three components, at different depths, that need this value?
- Does the value change rarely compared with how often the UI renders?
- Would the component still make sense if I read its props alone?
If the answer to the first is no, use props or composition. If the answer to the second is no, use local state or a store. If the third is no, think about whether the hidden dependency is worth it.
Exercise
A SearchBox component holds the current query string, which changes on every keystroke. Three components far down the tree display results for that query, and you put the query in a context. Typing feels slow. Why, and what are two ways to fix it?
Show answer
Every keystroke changes the context value, so every component that calls useContext for it re-renders, including components that read only other parts of the value. Two fixes: keep the query in local state and pass only the submitted or debounced query through context, or move the query into an external store and have each result component subscribe with a selector. Splitting the context also helps when unrelated data shares the same provider.
Exercise
A Dashboard passes a user prop to Sidebar, which passes it to UserMenu, which passes it to Avatar. Only Avatar uses user. Without context, how can you remove the forwarding?
Show answer
Build the element in Dashboard as <Avatar user={user} /> and pass it down as a prop or as children, for example <Sidebar menu={<UserMenu avatar={<Avatar user={user} />} />} />. Sidebar and UserMenu render the slot without knowing about user.
Exercise
Your provider fetches a product list in an effect and stores it in state. Name two features you would need to add yourself that TanStack Query provides.
Show answer
Any two of: caching shared between components, refetching on window focus or reconnect, request deduplication, ignoring stale or out-of-order responses, retries, and invalidating data after a mutation.