Context architecture and performance
Context is simple at the API level and architectural at the application level.
The difficult questions are not how to call createContext or useContext. They are about ownership, scope, update frequency, subscriptions, and coupling.
Provider placement is an ownership decisionβ
Consider cart state that only matters inside shop routes.
<Route
path="/shop/*"
element={
<CartProvider>
<Storefront />
</CartProvider>
}
/>
State locality applies to Context too. A provider at application root creates a broader dependency and longer lifetime than a feature-local provider.
Context value identityβ
React compares the previous and next provider value with Object.is.
<AuthContext value={{user, signOut}}>
The object is newly created whenever the provider renders.
This may be perfectly acceptable. Memoize only when profiling shows provider churn and consumer work are meaningful.
const value = useMemo(
() => ({user, signOut}),
[user, signOut],
);
React Compiler may reduce the need for some manual memoization. Treat memoization as a measured performance tool, not a correctness requirement.
Split unrelated contextsβ
A broad context couples values that change independently:
<AppContext value={{theme, user, cart, locale}}>
Do not create dozens of contexts mechanically. Split when domains have different owners, lifetimes, change patterns, or consumer groups.
Split state from dispatchβ
Reducer-based features can expose reads and writes through separate contexts.
const TasksContext = createContext(null);
const TasksDispatchContext = createContext(null);
function TasksProvider({children}) {
const [tasks, dispatch] = useReducer(tasksReducer, initialTasks);
return (
<TasksContext value={tasks}>
<TasksDispatchContext value={dispatch}>
{children}
</TasksDispatchContext>
</TasksContext>
);
}
The dispatch function returned by useReducer has stable identity, which makes it a natural write-only dependency.
Feature Hooks create a stronger boundaryβ
export function useTasks() {
const tasks = useContext(TasksContext);
if (tasks === null) throw new Error('useTasks must be used within TasksProvider');
return tasks;
}
export function useTasksDispatch() {
const dispatch = useContext(TasksDispatchContext);
if (dispatch === null) throw new Error('useTasksDispatch must be used within TasksProvider');
return dispatch;
}
Consumers depend on a feature API rather than the raw Context objects.
useContext is not a selector APIβ
const {theme} = useContext(AppContext);
Destructuring one field does not subscribe to only that field. The component reads the context value as a whole.
Context and memoβ
A component reading Context can update when that Context changes even if it is wrapped in memo.
const Product = memo(function Product() {
const currency = useContext(CurrencyContext);
// ...
});
memo compares props; Context is another input.
If profiling proves an expensive child needs prop-based memoization, split the context-reading container from the expensive view:
function ProductContainer() {
const currency = useContext(CurrencyContext);
return <ProductView currency={currency} />;
}
const ProductView = memo(function ProductView({currency}) {
// expensive render
});
High-frequency state may be a poor Context fitβ
Context can transport pointer coordinates or animation-frame data, but that does not mean it should.
High values make subscription granularity increasingly important.
A slowly changing theme and a 60Hz shared signal have very different architecture requirements.
Separate server state from client stateβ
Client state examples include open dialogs, selected tabs, drafts, and wizard steps.
Server state examples include inventory, customer records, order status, and analytics results.
If the hard problem is remote-data lifecycle, use the architecture/tool that owns that lifecycle rather than rebuilding a cache inside Context.
Provider composition is not automatically badβ
<AuthProvider>
<ThemeProvider>
<FeatureFlagsProvider>
<App />
</FeatureFlagsProvider>
</ThemeProvider>
</AuthProvider>
Multiple focused providers often communicate dependencies more clearly than one giant provider.
If readability becomes awkward, compose providers as a structural convenience without merging unrelated ownership.
Colocate providers with featuresβ
A feature-owned provider and its reducer/Hooks should usually live near that feature rather than in a universal contexts/ dump.
features/
cart/
CartProvider.jsx
useCart.js
cartReducer.js
auth/
AuthProvider.jsx
useAuth.js
This is a literal project structure, so text is the clearer format here.
Avoid provider side-effect overloadβ
A provider is still a component. Do not turn it into a giant service container that fetches every API, registers unrelated global listeners, owns many timers, and exposes hundreds of commands.
Keep each provider aligned with a coherent domain.
Performance debugging checklistβ
Use the React DevTools Profiler before adding memoization everywhere.
Architecture exampleβ
When should Context become an external store?β
Exerciseβ
Take one giant context containing user, theme, cart, activeModal, and products. Classify owner, scope, frequency, server/client origin, and subscriber needs for each value, then redesign the provider boundaries.
Interview questionsβ
Mid-level: Why can one giant Context cause unnecessary coupling?
Senior: How do Context value identity, provider scope, and consumer subscriptions influence rendering?
Staff: When would you move from Context to an external store, and how would you prove the migration is justified?
Summaryβ
Referencesβ
- https://react.dev/reference/react/useContext
- https://react.dev/learn/passing-data-deeply-with-context
- https://react.dev/learn/scaling-up-with-reducer-and-context
Nextβ
Continue with useReducer and Reducer Design.