Sub topic 10
Context changes and memoized components
This chapter assumes you know useState, props and children, and the basics of React.memo, useMemo and useCallback from earlier chapters. You should also be able to read a createContext and useContext example. The chapter covers how context updates interact with memoization, why memo cannot block them, and how to structure providers so that only the components that need an update re-render.
Context bypasses memo
React.memo compares a component's props. If they are shallowly equal to the previous props, React skips rendering that component. Context is a separate input. A component that calls useContext(SomeContext) subscribes to that context. When the value passed to the nearest SomeContext.Provider changes, React re-renders every consumer of that context. This happens even if a memo wrapper sits above the consumer and its props are identical.
React decides whether a context value changed with Object.is, the same comparison used for dependency arrays. For primitives, equal values count as unchanged. For objects, arrays and functions, only the same reference counts as unchanged.
Three rules follow:
memoprotects a component from re-renders caused by its parent. It does not protect it from re-renders caused by its own state, or by a context it reads.- A memoized component that does not read the context is not re-rendered by the context change. React only walks down to the consumers.
- A consumer re-renders when the context value changes, even if it only uses part of the value.
The most common bug: an unstable provider value
A provider often holds state and passes an object to its consumers. If you write the object inline, it is a new object on every render of the provider. Every consumer then re-renders whenever the provider's own parent re-renders, even if no state changed.
import { createContext, useContext, useMemo, useState } from 'react';
const ThemeContext = createContext(null);
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
// Broken: a new object on every render of ThemeProvider.
// <ThemeContext.Provider value={{ theme, setTheme }}>
// Fixed: the same object until `theme` changes.
// setTheme from useState is stable, so it is not a dependency.
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function useTheme() {
const ctx = useContext(ThemeContext);
if (ctx === null) {
throw new Error('useTheme must be used inside ThemeProvider');
}
return ctx;
}This is one of the clearest cases where useMemo is worth writing. The cost is a dependency array and a small cache. The benefit is that consumers re-render only when theme changes.
If the context value includes functions you define in the provider, wrap them in useCallback and list them in the useMemo dependencies. Otherwise the memoized object changes whenever the function identity changes.
When the provider's parent re-renders
Consider this tree:
function App() {
const [tick, setTick] = useState(0);
return (
<>
<button onClick={() => setTick(tick + 1)}>Tick {tick}</button>
<ThemeProvider>
<Header />
<Content />
</ThemeProvider>
</>
);
}When tick changes, App re-renders and creates new <Header /> and <Content /> elements. ThemeProvider re-renders too, because it receives a new children prop. With the memoized value above, the context itself did not change. Header and Content still re-render, because they are new elements produced by App, unless they are wrapped in memo.
Now suppose the ThemeProvider state changes instead. ThemeProvider re-renders, but its children prop is the same reference as before, because App did not re-render. React reuses those elements and skips them. Only components that consume ThemeContext re-render. This is why the provider-with-children pattern is useful. The provider owns the state, and the rest of the tree is passed in from outside, so state updates do not re-render unrelated components.
Split contexts by how often they change
A context value is all or nothing. If one context holds both count and dispatch, a component that only needs dispatch still re-renders on every count change. A common fix is to use two contexts: one for state, one for dispatch.
import { createContext, useContext, useReducer } from 'react';
const CountStateContext = createContext(0);
const CountDispatchContext = createContext(null);
function reducer(count, action) {
switch (action.type) {
case 'increment':
return count + 1;
case 'reset':
return 0;
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
export function CountProvider({ children }) {
const [count, dispatch] = useReducer(reducer, 0);
return (
<CountDispatchContext.Provider value={dispatch}>
<CountStateContext.Provider value={count}>
{children}
</CountStateContext.Provider>
</CountDispatchContext.Provider>
);
}
export function CountDisplay() {
const count = useContext(CountStateContext);
console.log('render CountDisplay');
return <p>Count: {count}</p>;
}
export function IncrementButton() {
const dispatch = useContext(CountDispatchContext);
console.log('render IncrementButton');
return <button onClick={() => dispatch({ type: 'increment' })}>Add one</button>;
}
export default function App() {
return (
<CountProvider>
<CountDisplay />
<IncrementButton />
</CountProvider>
);
}The dispatch function from useReducer is stable for the life of the component, so CountDispatchContext never changes. Clicking the button logs render CountDisplay only. IncrementButton does not re-render because its context did not change and App did not re-render it.
Splitting contexts works best along a clear line, such as "changes often" versus "never changes", or "read" versus "write". Splitting into many tiny contexts adds nesting and makes the code harder to follow. Do it when you have measured a problem.
Memo as a barrier between a context and expensive children
Sometimes a component reads a context and also renders an expensive child that does not need that context. The consumer re-renders on every context change, and so does its child, unless you stop it.
import { memo, useContext } from 'react';
import { ThemeContext } from './theme';
const Chart = memo(function Chart({ data }) {
// Expensive rendering, does not read ThemeContext.
return <canvas data-points={data.length} />;
});
export function ThemedPanel({ data }) {
const { theme } = useContext(ThemeContext);
return (
<section className={theme}>
<Chart data={data} />
</section>
);
}When the theme changes, ThemedPanel re-renders because it consumes the context. Chart is memoized and data is the same reference, so Chart is skipped. This is the correct use of memo with context: you cannot stop the consumer, but you can stop its children from following it.
A related pattern is to read the context in a small wrapper component and pass the relevant slice down as a prop to a memoized component. React has no built-in selector for useContext, so you cannot subscribe to a single field. The wrapper approach gives you a similar effect for the part of the tree below it.
import { memo, useContext } from 'react';
import { SettingsContext } from './settings';
const Price = memo(function Price({ currency, amount }) {
return <span>{amount} {currency}</span>;
});
export function PriceContainer({ amount }) {
const { currency } = useContext(SettingsContext);
return <Price currency={currency} amount={amount} />;
}PriceContainer still re-renders on any change to SettingsContext. Price re-renders only when currency or amount changes.
Edge cases
- Custom comparison does not help. A comparison function passed to
memoonly sees props. It cannot prevent a context-driven render, so do not try to fix a context problem there. - Default values. A consumer with no provider above it receives the default passed to
createContext. That value never changes, so the consumer does not re-render because of the context. - Multiple providers of the same context. Each consumer reads the nearest provider. A change in an outer provider does not re-render consumers that sit under an inner provider of the same context, unless the inner provider's own value depends on it.
- A new provider value on each render of a high-level component. A root-level provider whose parent re-renders often, for example one that sits beside a ticking clock, can cause the whole app to re-render. Check where the provider's state lives and whether its value is memoized.
- Objects that mix fast and slow data. If one value contains a mouse position along with settings, every consumer re-renders on every mouse move. Separate the two.
Choosing a fix
| Symptom | Likely cause | Fix |
|---|---|---|
| All consumers re-render when an unrelated parent updates | Inline object as `value` | `useMemo` for the value |
| A component using only `dispatch` re-renders on state change | State and dispatch share one context | Split into two contexts |
| Non-consumers re-render when provider state changes | Provider renders children it created itself | Pass `children` in from outside |
| An expensive child re-renders with its consumer parent | Child is not memoized | `memo` on the child with stable props |
| A consumer needs one field of a large value | `useContext` has no selector | Split the context or use a wrapper component |
Exercise
A UserProvider holds const [user, setUser] = useState(null) and renders <UserContext.Provider value={{ user, setUser }}>{children}</UserContext.Provider>. The App component above it re-renders every second because of a clock. Every consumer of UserContext re-renders each second, even though user has not changed, and wrapping the consumers in memo does not help. Why, and what is the fix?
Show answer
The object literal { user, setUser } is created again each time UserProvider renders. UserProvider re-renders because App re-renders it. The new reference fails the Object.is check, so React treats the context as changed and re-renders every consumer. memo does not apply because context updates bypass it. Fix: const value = useMemo(() => ({ user, setUser }), [user]); and pass value to the provider. setUser is stable, so it does not need to be listed.
Exercise
A Toolbar component reads CountStateContext to show a count, and it renders <HeavyPreview data={data} />, which does not use the context. HeavyPreview re-renders every time the count changes. What change stops this, and what must be true of data?
Show answer
Wrap HeavyPreview in memo. Toolbar still re-renders on every count change because it consumes the context, but HeavyPreview is skipped if its props are shallowly equal. This requires data to keep the same reference between renders, for example because it comes from props or state, or is created with useMemo. A freshly created array or object each render would defeat memo.