Sub topic 10
Context changes and memoized components
This chapter assumes you know function components, useState, props and children, and how React.memo compares props shallowly. Here you will see how context updates interact with memo, and how to limit the re-renders they cause.
Context bypasses memo
React.memo skips a re-render when props are unchanged. It does not protect a component from context. When a component calls useContext(SomeContext), React re-renders it whenever the context value changes, even if memo wraps it and its props are identical.
Context is a second input channel to a component. memo guards only the props channel.
import { createContext, memo, useContext, useState } from 'react';
const ThemeContext = createContext('light');
const Toolbar = memo(function Toolbar({ title }) {
const theme = useContext(ThemeContext);
console.log('render toolbar');
return <h1 className={theme}>{title}</h1>;
});
export function App() {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle
</button>
<Toolbar title="Home" />
</ThemeContext.Provider>
);
}Clicking the button changes the context value, so Toolbar renders again. That is correct here, because it displays the theme. A problem appears only when a component re-renders for context changes it does not need.
How React decides who re-renders
React compares the provider's value with Object.is. If the value is a new reference, every component that reads that context re-renders. Components that do not call useContext for it are unaffected by the context itself. They re-render only if a parent re-renders them.
flowchart TDUse the diagram below to follow one update.
The unstable value problem
The most common error is passing a fresh object to the provider on every render. The context value changes by reference each time the parent renders, even if its contents are the same.
import { createContext, useMemo, useState } from 'react';
export const UserContext = createContext(null);
export function UserProvider({ children }) {
const [name, setName] = useState('Ada');
// Broken: a new object each render, so every consumer re-renders
// whenever UserProvider renders.
// const value = { name, setName };
// Fixed: the same object until name changes.
const value = useMemo(() => ({ name, setName }), [name]);
return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}setName from useState is already stable, so it does not need to be in the dependency array. Because children comes from outside the provider, a parent re-render that passes the same children elements does not force them to re-render. The same reasoning appears in the composition technique from the previous chapter.
Limiting the blast radius
When a context holds several unrelated values, every consumer re-renders when any one changes. You have three practical options.
- Split the context. Keep values that change at different rates in separate contexts, such as one for the current user and another for the theme. A component reads only what it needs.
- Separate state from actions. Put the changing state in one context and the stable setter functions in another. Components that only dispatch updates then ignore state changes.
- Pass a memoized subtree. Read the context in a small wrapper, then pass the needed value down as a prop to a
memocomponent. The memoized child re-renders only when that specific value changes.
The third option looks like this:
import { memo, useContext } from 'react';
import { UserContext } from './UserContext';
const Greeting = memo(function Greeting({ name }) {
console.log('render greeting');
return <p>Hello, {name}</p>;
});
export function GreetingContainer() {
const { name } = useContext(UserContext);
return <Greeting name={name} />;
}GreetingContainer is cheap and re-renders on every context change. Greeting may be expensive, and memo skips it unless name changes. Here memo works because the context value has been converted into an ordinary prop.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Every consumer re-renders when the provider's parent renders | Inline object in `value` | Wrap the value in `useMemo` |
| `memo` on a consumer has no effect | Context bypasses `memo` | Split the context or pass a prop from a wrapper |
| Components that ignore a context value still re-render | One large context holds everything | Split into smaller contexts |
Exercise
A memo-wrapped Sidebar calls useContext(SettingsContext) and only displays settings.language. The provider holds { language, fontSize }, and changing fontSize re-renders Sidebar. Why does memo not prevent this, and how would you stop it?
Show answer
memo only compares props, and Sidebar re-renders because the context value changed. Fix it by splitting language and fontSize into separate contexts, or by reading the context in a small wrapper component that passes settings.language to a memo version of Sidebar as a prop. The prop stays the same string when only fontSize changes, so memo skips the render.
Exercise
A provider sets value={{ user, logout }} inline. Its parent re-renders often for unrelated reasons. What happens to consumers, and what is the fix?
Show answer
Each parent render creates a new object, so Object.is reports a changed value and every consumer re-renders. Wrap the value in useMemo(() => ({ user, logout }), [user, logout]), and make logout stable with useCallback if it is defined inside the component.