Context Without the Re-render Tax
How context actually propagates updates, why a fresh value object re-renders every consumer, and the state/dispatch split that keeps distant components cheap.
Contentsand lesson path
On this page
- Why it matters
- The one rule: value identity
- Split state from dispatch
- Scope the provider, then measure
- Check your understanding
- Apply it
- Review prompt
Lessons of Frontend State Management
- Where Should This State Live? Concept · 20 min
- Reducers for Complex Transitions Worked example · 25 min
- Context Without the Re-render Tax Concept · 20 min
- External Stores and Selectors Worked example · 25 min
- Lab: Untangle a Prop-Drilled Cart Lab · 30 min
- Check: State Placement Scenarios Knowledge check · 6 questions
What you will learn
- Model complex state transitions with useReducer and typed actions, and share them through context without unnecessary re-renders.
Prerequisites: React Components & State
01. Why it matters
Lesson 1 ended with a value that is genuinely shared client state: owned by the browser, read in several distant places. The built-in answer is context — create one, wrap the tree in a provider, and any component underneath can read the value without a single drilled prop. The reducer from the last lesson slots in directly: hold it in a provider component, share state and dispatch through context.
Context has a cost model, though, and it is stricter than most people expect: every consumer re-renders whenever the context value changes — whichever field it reads, however small the change, and memo on a consumer does not block it, because the consumer subscribes to the context itself, not to props. Used carelessly, one fast-changing context turns the whole tree beneath it into a re-render storm. Used deliberately, the same primitive with two small habits splits cleanly. This lesson builds that judgement with measured results, not folklore: every render count below was observed by running the components under Testing Library with a render counter.
02. The one rule: value identity
React compares the value you give the provider with the previous one using Object.is — identity, not contents. If the identity is unchanged, nothing below re-renders. If it changed — even to a logically equal object — every consumer re-renders. That single rule explains both classic surprises. A primitive (theme, locale) is cheap: a string that stays 'light' keeps its identity forever, so consumers re-render only when it genuinely changes. A fresh object literal in JSX is expensive:
const Caption = memo(function Caption() {
const { theme } = useContext(ThemeContext);
console.log('render Caption');
return <p>{theme}</p>;
});
function App() {
const [draft, setDraft] = useState('');
return (
<>
<input aria-label="Draft" value={draft}
onChange={(e) => setDraft(e.target.value)} />
{/* new object identity on every keystroke: */}
<ThemeContext value={{ theme: 'light' }}>
<Caption />
</ThemeContext>
</>
);
}render Caption
render Caption
render CaptionNotice that Caption is wrapped in memo. Normally, memo prevents parent re-renders from cascading into children when props are unchanged. But because App passes an inline { theme: 'light' } object literal, each render produces a new object identity. Context subscriptions bypass memo entirely and re-render Caption on every keystroke. (Since React 19 the context object itself is the provider, as in <ThemeContext value={…}>; the older <ThemeContext.Provider value={…}> spelling still works and behaves the same, and the logs above were the same with both.) Two standard fixes: move the object up out of render (const value = useMemo(() => ({ theme }), [theme])), or pass the primitive itself (value="light") where memo can successfully bail out.
03. Split state from dispatch
A reducer brings a gift most people overlook: dispatch never changes. React guarantees a stable identity for it across renders, so a component that only dispatches never needs to hear about state changes at all. Giving both values one context object throws that away. The fix is two providers, and two hooks that read them:
const CartStateContext = createContext<CartState | null>(null);
const CartDispatchContext =
createContext<((action: CartAction) => void) | null>(null);
export function CartProvider({ children }: { children: ReactNode }) {
const [cart, dispatch] = useReducer(cartReducer, emptyCart);
return (
<CartDispatchContext value={dispatch}>
<CartStateContext value={cart}>
{children}
</CartStateContext>
</CartDispatchContext>
);
}
export function useCartState(): CartState {
const cart = useContext(CartStateContext);
if (!cart) throw new Error('useCartState needs <CartProvider>');
return cart;
}
export function useCartDispatch() {
const dispatch = useContext(CartDispatchContext);
if (!dispatch) throw new Error('useCartDispatch needs <CartProvider>');
return dispatch;
}The hooks earn their keep twice over: the null checks turn "forgot the provider" into an error message instead of a crash three files away, and call sites never see the context objects. The measured difference under Testing Library, with a badge that reads state and two buttons that only dispatch, two Add clicks and one Clear:
render AddButton
render ClearButton
render CartBadge
render CartBadge
render CartBadge
render CartBadgeSix lines, and the two dispatch-only buttons appear exactly once — at mount. They never re-render on any number of cart changes because the dispatch function they read never changes. Notice why the provider's own re-render does not walk down into the buttons: CartProvider renders {children}, and because those elements were created by the parent rather than inside CartProvider, React automatically bails out of re-rendering {children} (the children-prop bailout). Split contexts handle the context route, while {children} preserves the component tree. And the state context value is the reducer's cart object — a new identity on every change, which is exactly what the badge wants to hear about.
04. Scope the provider, then measure
Two habits keep the re-render tax low. First, put the provider as low as the tree allows. A sort order shared by one page's toolbar and table belongs to that page, not the app root; everything outside the provider never re-renders for it at all. App-wide state stays app-wide; page state stays on the page. Second, split by change rate, not by topic: a locale that changes at sign-in and a cart that changes per click must not share one context, or every cart click re-renders the locale readers.
Then verify instead of trusting. A one-line render counter (console.log inside the component body while developing) shows the truth immediately, as the logs above do; React Developer Tools has a profiler and a "why did this render" hint that names context changes. The rule you are checking for is the one this lesson opened with: consumers re-render when value identity changes. When that is too coarse — many components reading different slices of fast-changing state — context has no mechanism to help, because there is no selector. That is the cue for external stores and selectors, and the lab applies the whole split to a real cart.
05. Check your understanding
06. Apply it
Find one context (or one prop chain) in your own work that mixes a fast-changing value with a slow one, and split it: two providers, two hooks with null checks, dispatch in its own context if there is a reducer. Add a temporary render counter to three consumers, click through a normal flow, and write down the before-and-after render counts. The practice brief asks for this split on the cart; the lab walks it, and the render logs in this lesson are the expected shape of the result.
07. Review prompt
Without looking back: state the one rule of context updates. Explain why { theme: 'light' } inline in JSX re-renders every consumer while theme alone does not, why dispatch is safe to put in its own context, and what memo does and does not block.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.