Skip to main content

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.

The real Context design questions
Ownership
Who actually owns and changes this state?
Scope
Which subtree needs access?
Change pattern
Which consumers should update together?
Read/write API
Should reading and dispatching be separate dependencies?
Frequency
How often does this value change?
Fit
Is this really Context-shaped data?

Provider placement is an ownership decision​

Consider cart state that only matters inside shop routes.

Place providers at the smallest useful scope
App
Marketing
does not need cart
Storefront + CartProvider
ProductPage Β· CartDrawer Β· Checkout
Admin
does not need cart
<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.

Provider render does not always mean context value stability
1provider renders
2value expression creates object
3Object.is compares identity
4consumers can receive update

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}}>
Split independent domains instead of one mega-context
Theme
Auth
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>
);
}
Separate read and write dependencies
State Context
Consumers that render from tasks subscribe to task state.
Dispatch Context
Dispatch-only consumers receive the stable dispatch function.

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.

Consumers need different slices of rapidly changing shared stateβ€”what next?
Domains are actually independentSplit contexts
State can move closer to the consumersPrefer locality
Fine-grained subscriptions are a core requirementEvaluate an external store / library with selector semantics

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.

Shared-state rendering pressure
frequency Γ— subscriber count Γ— render cost

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.

Context transports values; it does not create a server-state lifecycle
Context
Tree distribution + subscriptions to one provider value.
Server-state lifecycle
fetching Β· caching Β· staleness Β· invalidation Β· retries Β· background refresh

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​

Context performance debugging flow
1Which provider rendered?
2Why did it render?
3Did value identity change?
4Which consumers read it?
5Are those renders expensive?
6Can ownership/scope be improved first?

Use the React DevTools Profiler before adding memoization everywhere.

Architecture example​

Provider scope should narrow as ownership narrows
BROAD ENVIRONMENTAuthProvider
wraps routing / authenticated application scope
FEATURE ENVIRONMENTDashboardPreferencesProvider
only dashboard descendants depend on it
LOCAL FEATURE STATESelectedProjectProvider
only the project subtree needs it

When should Context become an external store?​

Is Context still a good subscription model?
Moderate updates, coherent subtree, full-value subscriptions are fineContext can remain a strong fit
Provider is too broad but ownership can be narrowedFix provider scope first
Many consumers need independent slices / high-frequency updates / non-React accessEvaluate 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​

Context architecture sequence
1choose the owner
2place provider at smallest useful scope
3split unrelated domains
4separate read/write APIs when useful
5measure rendering
6change state model only with evidence

References​

Next​

Continue with useReducer and Reducer Design.