Context Performance and Selective Subscriptions
Build, explain and debug React 19 interfaces: components, rendering, state, effects, identity, forms and actions, server components, concurrency, performance and testing, ending with architecture and typing work on real component challenges.
What you will be able to do
#- Explain why every context consumer re-renders on a value change.
- Split context and memoize provider values to reduce re-renders.
- Choose an external store when selective subscriptions are needed.
Overview
#Every consumer re-renders on a value change
When a context value changes, React re-renders every component that reads that context, even if the part the component uses did not change. Context has no built-in selector. This is the main performance cost of context.
const ThemeContext = createContext<{ theme: string; setTheme: (t: string) => void }>({ theme: 'light', setTheme: () => {} });
Split value and dispatch
If some consumers only need a setter, put the setter in its own context. The setter is stable, so its context value never changes and those consumers never re-render when the value changes.
const ValueContext = createContext(0);
const DispatchContext = createContext<(a: Action) => void>(() => {});
Memoize the provider value
A provider whose value is a new object every render re-renders every consumer on every parent render, even when nothing meaningful changed. Wrap the value in useMemo.
const value = useMemo(() => ({ theme, setTheme }), [theme]);
<ThemeContext value={value}>...</ThemeContext>
The children trick
If a provider component holds state and also renders children, the children re-render when the state changes. Passing children from the parent instead means the parent creates the elements, so they are not re-rendered by the provider's state.
function Provider({ children }: { children: React.ReactNode }) {
const [state, setState] = useState(0);
return <Ctx value={state}><button onClick={() => setState(state + 1)}>{state}</button>{children}</Ctx>;
}
Pitfall: expecting context selectors
React context does not support selectors like a store does. If a component must subscribe to one slice of frequently changing data, use useSyncExternalStore with a store that supports selectors instead.
Pitfall: one giant context
A single context for unrelated values re-renders every consumer on any change. Split by concern and by change frequency.
Exercises
#Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.
Exercise 1Predict
Which consumers re-render when theme changes?
Read the code, then choose the best answer. The reference explanation stays hidden until you respond. stimulus.tsxconst Ctx = createContext<{ theme: string; user: User }>(...); function Header() { const { user } = useContext(Ctx); return <span>{user.name}</span>; } function Banner() { const { theme } = useContext(Ctx); return <div data-theme={theme} />; }Exercise 2Implement
Split this context so consumers that only dispatch do not re-render when the value changes.
starter.tsxconst Ctx = createContext<{ count: number; inc: () => void }>({ count: 0, inc: () => {} });Reveal the reference answer
reference.tsxconst CountContext = createContext(0); const IncContext = createContext<() => void>(() => {}); function Provider({ children }: { children: React.ReactNode }) { const [count, setCount] = useState(0); const inc = useCallback(() => setCount((c) => c + 1), []); return ( <CountContext value={count}> <IncContext value={inc}>{children}</IncContext> </CountContext> ); }Authored expected output: Components that only call inc do not re-render when count changes.
The inc function is stable, so the IncContext value never changes. Dispatch-only consumers subscribe to a context that does not change and therefore do not re-render when count updates.
Exercise 3Debug
This provider re-renders every consumer on every parent render. Explain and fix.
starter.tsx<ThemeContext value={{ theme, setTheme }}>{children}</ThemeContext>Reveal the reference answer
reference.tsxconst value = useMemo(() => ({ theme, setTheme }), [theme]); return <ThemeContext value={value}>{children}</ThemeContext>;Authored expected output: Consumers re-render only when theme actually changes.
The inline object is a new reference on every render, so React sees a changed context value each time. useMemo keeps the reference stable until theme changes.
Exercise 4Interview
A dashboard uses one context for user, theme and notifications and feels slow. Walk through your fix.
starter.tsx// one AppContext with three unrelated valuesReveal the reference answer
reference.tsxFirst profile to confirm that unrelated consumers re-render. Then split the context by concern so a notification change does not re-render theme consumers. Memoize each provider value so parent renders do not create new references. For values that change frequently and are read by many components, move them to an external store with useSyncExternalStore so components can subscribe to just the slice they need. Re-profile to confirm the re-render scope shrank.Authored expected output: A measured plan: profile, split by concern, memoize values, use a store for high-frequency slices, re-verify.
The fixes are ordered by effort: split and memoize first, then reach for a store when context's lack of selectors is the real problem.
Common misconceptions
#- Context only re-renders consumers that use the changed field. Context re-renders every consumer of that context.
- Memoizing the value fixes all re-renders. It prevents provider-driven re-renders, not value-change re-renders.
- Context supports selectors. It does not; use an external store for selective subscriptions.
- Splitting context is over-engineering. Splitting by concern and change frequency is the standard fix.
Follow-up practice
#- react-external-stores
- react-component-architecture
Your progress
#Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.
Verification: authored. Answers and outputs on this page are authored reference material, not executed results.