What You'll Learn
- 1Frame context as dependency injection rather than as a global variable
- 2Choose a default value strategy that surfaces missing providers in development
- 3Explain the re-render cost of a context value and split providers to reduce it
- 4Test a consumer component without rebuilding the whole provider tree
Context is dependency injection
Context solves one problem well: passing a value through many layers of components that will never display it. The alternative, prop drilling, forces every intermediate component to accept, forward, and remember a prop it does not use, which couples those components to a child they have no interest in.
The mental model that keeps context honest is dependency injection. A provider declares an implementation of a capability, such as an authentication session, a theme, or a feature flag service, and the components below consume it the way they would consume any imported module. That framing keeps you away from the temptation to put the entire application state into one context, which is how context earns its reputation as a slow global store.
Context shines for values that change rarely and are read widely. It is a poor fit for anything updated on every keystroke, because every consumer commits a render whenever the value is replaced.
Defaults, and the missing-provider trap
createContext accepts a default value used by any consumer that sits above every provider. That default is convenient for prototyping and dangerous in production, because a component that works in isolation but fails in the app is a debugging session nobody budgeted for.
import { createContext, useContext, useEffect, useState } from 'react';
const ThemeContext = createContext(undefined);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState(() =>
typeof window === 'undefined' ? 'light' : window.localStorage.getItem('theme') || 'light'
);
useEffect(() => {
window.localStorage.setItem('theme', theme);
document.documentElement.dataset.theme = theme;
}, [theme]);
const value = { theme, toggle: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')) };
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (ctx === undefined) {
throw new Error('useTheme must be used inside ThemeProvider');
}
return ctx;
}
Passing undefined as the default and throwing in a wrapper hook turns a silent misconfiguration into an immediate, named error. Wrapping the consumer is worth the twelve lines in every context you write for more than one team member.
Why every consumer re-renders
Context has no selectors. When a provider's value changes, every component that called useContext on that context re-renders, regardless of which field of the value it actually reads. This is the single most important performance fact about the API.
| Cause of a consumer render | Frequency | Mitigation |
|---|---|---|
| Provider value is a new object each render | Every parent render | Memoise the value, or move unstable parts into a separate context |
| Consumer reads only a field that did not change | Any provider update | Split the value into contexts per concern, or subscribe to a store instead |
| Provider is mounted high in the tree and re-renders often | Common in large apps | Keep the provider near its consumers, or stabilise its own state |
| Value includes functions recreated inline | Every render | Wrap handlers in useCallback before putting them in the value |
| Theme or locale changes intentionally | Rare | No fix needed; a full re-render is correct here |
A useful rule of thumb: a context value should change at the rate its slowest consumer expects, not at the rate its fastest writer updates. If those rates differ by orders of magnitude, they belong in different contexts.
Splitting value from dispatch
The most common fix, and the one with the best ratio of effort to result, is to publish state and dispatcher through separate contexts. Consumers that only fire actions read the dispatcher context, whose value is stable for the lifetime of the provider, so they skip every state update.
const CountStateContext = createContext(0);
const CountDispatchContext = createContext(null);
function CountProvider({ children }) {
const [count, setCount] = useState(0);
const dispatch = useMemo(
() => ({
increment: () => setCount((c) => c + 1),
decrement: () => setCount((c) => c - 1),
reset: () => setCount(0),
}),
[]
);
return (
<CountStateContext.Provider value={count}>
<CountDispatchContext.Provider value={dispatch}>
{children}
</CountDispatchContext.Provider>
</CountStateContext.Provider>
);
}
function useCount() {
return useContext(CountStateContext);
}
function useCountActions() {
const actions = useContext(CountDispatchContext);
if (!actions) throw new Error('useCountActions requires CountProvider');
return actions;
}
Pair this with useReducer when the state is more than a single value. The reducer keeps related fields consistent, and because dispatch is stable, the dispatch context never notifies anyone.
Narrowing the blast radius further
Splitting value from dispatch reduces renders but does not address the underlying subscription model. Three further techniques cover the remaining cases. Move the provider down the tree so only the subtree that reads the value sits beneath it. Split a composite value into several contexts by concern, so a change to the user object does not disturb components that only wanted the locale. And when the value changes on nearly every interaction, replace context with a selector store, which re-renders only the components whose selected slice actually differs.
None of these require abandoning context. Most applications end up with a handful of slow-moving contexts at the root, a couple of scoped providers inside feature branches, and an external store for the fast-changing shared data.
Scoped providers, and composing several applications
Providers do not have to live at the root. Mounting one inside a branch scopes its value to that subtree, which is how design systems ship a theme override for a single panel, and how multi-tenant dashboards render a second workspace with a different configuration without unmounting the page around it.
Scoping creates a second context value that shadows the outer one, and that is worth being deliberate about. A component rendered inside the inner provider cannot reach the outer value at all, which is usually what you want and occasionally a surprise when a deeply nested widget expected the global session. Naming helps: if two providers can supply the same capability, distinguish them explicitly in the file names and in the hook names, rather than relying on import order to decide which one wins.
Composition also interacts with portals. Portal children keep their React parentage, so a portal rendered inside a scoped provider still reads the scoped value, even though its markup sits at the end of the document. That is frequently the behaviour you want for a dialog that belongs to a workspace, and it is worth verifying once with a test rather than assuming either way.
One structural warning: a provider that mounts a large subtree and swaps its value frequently will re-render that entire subtree. If a scoped provider must update on every interaction, give it the narrowest possible value, or replace it with a store whose consumers subscribe to slices. Scope solves reach, not frequency.
Testing consumers in isolation
A consumer that throws outside its provider is easier to test than one that silently reads a default, because the test setup states its assumptions. Build a tiny harness that mounts the real provider with a controllable initial value, render the component inside it, and assert on what the user sees rather than on internal state.
function renderWithProviders(ui, { theme = 'light' } = {}) {
return render(
<ThemeProvider initialTheme={theme}>
{ui}
</ThemeProvider>
);
}
test('renders the dark surface when the theme is dark', () => {
renderWithProviders(<SettingsPanel />, { theme: 'dark' });
expect(document.querySelector('[data-theme]')).toHaveAttribute('data-theme', 'dark');
});
If the harness needs to control the value rather than just the initial state, expose a settable wrapper in the test only. Resist adding test hooks to production code for a convenience you can get from a small local provider.
â ī¸Context is not a cache
Values stored in context are not reactive to anything outside React. If you put a server response there, two components will eventually disagree about whether it is fresh. Let a query library own server data and keep context for application configuration and capabilities.
Common Mistakes
Putting every piece of application state into a single root context
Fix: Split by concern and by change rate, and keep server data in a cache layer
Passing a fresh object literal as the provider value on every render
Fix: Memoise the value with useMemo and wrap handlers in useCallback before passing them down
Relying on the createContext default so components work without a provider
Fix: Pass undefined, throw in a wrapper hook, and fail loudly in development
Reaching for context to share state between two components that share a parent
Fix: Lift the state to that parent, which is simpler and does not notify the whole tree
Best Practices
- Export a useX hook alongside every context so consumers get a clear error and a stable API
- Keep context values small and publish dispatch separately from state
- Mount providers as close to their consumers as the component structure allows
- Memoise values that contain more than one primitive or any function
- Document the change rate of each context in a comment so future edits respect it
Key Takeaways
- Context is dependency injection for values that change slowly and are read widely
- A default of undefined plus a throwing hook surfaces missing providers immediately
- Every consumer re-renders when the value is replaced, because context has no selectors
- Splitting state and dispatch into two contexts removes most accidental renders
- Server data belongs in a query cache, not in context