Sub topic 8
How context updates cause re-renders
This chapter assumes you know createContext, Provider and useContext at a basic level, and that you know useState and how a parent re-render normally re-renders its children. Here you will learn exactly which components re-render when a context value changes, and which ones do not. The next chapters build on this to fix wasted renders.
The core rule
React compares the value prop of a Provider with its value from the previous render, using Object.is. If the two are the same, nothing happens. If they differ, React finds every component below that Provider that calls useContext for that context and re-renders it.
Three details follow from this rule:
- The check is by identity, not by contents. Two objects with the same fields are still different values.
- The consumer is scheduled for re-render directly. It does not matter whether the components between the Provider and the consumer re-render.
- A component reads the whole value. React has no built-in way to subscribe to one field of an object.
A first experiment
The following example logs each render so you can see who re-renders. Run it in a Vite or Create React App project and open the browser console.
import { createContext, memo, useContext, useState } from 'react';
const CountContext = createContext(0);
function CountProvider({ children }) {
const [count, setCount] = useState(0);
return (
<CountContext.Provider value={count}>
<button onClick={() => setCount(count + 1)}>Increment</button>
{children}
</CountContext.Provider>
);
}
function Display() {
const count = useContext(CountContext);
console.log('Display rendered');
return <p>Count: {count}</p>;
}
const MemoDisplay = memo(function MemoDisplay() {
const count = useContext(CountContext);
console.log('MemoDisplay rendered');
return <p>Memoized count: {count}</p>;
});
function Static() {
console.log('Static rendered');
return <p>I never read the context</p>;
}
export default function App() {
return (
<CountProvider>
<Display />
<MemoDisplay />
<Static />
</CountProvider>
);
}Click the button once. The console shows Display rendered and MemoDisplay rendered, but not Static rendered.
There are two separate reasons for this result.
MemoDisplayis wrapped inmemo, yet it still re-rendered.memoonly skips renders caused by a parent re-rendering with unchanged props. A context change does not go through props, somemocannot block it.Staticdid not re-render even though it is not memoized.CountProviderre-rendered because its state changed, butchildrenis a prop created byApp.Appdid not re-render, so the<Static />element is the same object as before, and React skips it.
What happens during an update
The sequence below shows one click in the example above.
Why identity matters: the inline object pitfall
Primitive values such as numbers and strings compare by value, so Object.is(1, 1) is true. Objects, arrays and functions compare by reference. A literal written in JSX creates a new reference on every render.
import { createContext, useContext, useState } from 'react';
const UserContext = createContext(null);
function Layout({ user, children }) {
// A new object is created every time Layout renders.
return (
<UserContext.Provider value={{ user }}>
{children}
</UserContext.Provider>
);
}
function Avatar() {
const { user } = useContext(UserContext);
console.log('Avatar rendered');
return <span>{user.name}</span>;
}
export default function App() {
const [seconds, setSeconds] = useState(0);
const [user] = useState({ name: 'Ada' });
return (
<>
<button onClick={() => setSeconds(seconds + 1)}>
Seconds: {seconds}
</button>
<Layout user={user}>
<Avatar />
</Layout>
</>
);
}Each click re-renders App, which re-renders Layout with the same user. The content of the value did not change, but { user } is a new object, so Object.is returns false and Avatar re-renders every time.
The fix is to keep the reference stable until its contents change. The useMemo hook does this:
import { useMemo } from 'react';
function Layout({ user, children }) {
const value = useMemo(() => ({ user }), [user]);
return (
<UserContext.Provider value={value}>
{children}
</UserContext.Provider>
);
}Now value is recreated only when user changes. We cover this pattern in detail in a later chapter. The point here is to recognize the cause.
Whole-value subscription
A consumer re-renders when the value changes, even if it only uses part of it. Suppose a provider shares one object:
const value = useMemo(
() => ({ user, theme, setTheme }),
[user, theme]
);A component that reads only user still re-renders when theme changes, because the object as a whole is new. There is no selector argument to useContext. Reading const { user } = useContext(AppContext) does not narrow the subscription.
Two common ways to deal with this are:
- Split the data into several contexts, grouped by what changes together. A later chapter covers this.
- Move the expensive part of the consumer into a memoized child and pass it the specific values as props. The consumer re-renders, but the memoized child skips work if its props are the same.
import { memo, useContext } from 'react';
const ExpensiveList = memo(function ExpensiveList({ user }) {
// heavy rendering that depends only on user
return <ul><li>{user.name}</li></ul>;
});
function Sidebar() {
const { user } = useContext(AppContext);
return <ExpensiveList user={user} />;
}Sidebar re-renders when theme changes, but ExpensiveList receives the same user reference and is skipped.
Reference table
| Situation | Do consumers re-render? | Why |
|---|---|---|
| Provider value is the same primitive as before | No | `Object.is` returns `true` |
| Provider value is a new object each render | Yes | New reference, even with equal contents |
| Consumer is wrapped in `memo` | Yes | `memo` checks props, not context |
| Component is between the provider and consumer and does not read context | Only if its parent re-renders it | It is not subscribed |
| Component reads a different context | No | Each context is tracked separately |
| Provider is re-rendered by its parent, value unchanged by identity | No | Consumers compare the value, not the parent render |
The last row is worth checking. A provider can re-render without its consumers re-rendering through context. They may still re-render for ordinary reasons, such as being rendered inline by that same parent.
Default values do not drive updates
The default value passed to createContext is used only when a component has no Provider above it. It never changes, and changing it does not cause renders. All updates come from a Provider's value. If you see a consumer stuck on the default, check that it is actually rendered inside the Provider.
Finding unnecessary renders
Use the React DevTools Profiler to check your assumptions. Turn on recording, perform the interaction, and look at which components rendered. Selecting a component in a profile shows why it rendered, and context changes appear in that explanation. You can also enable "Highlight updates when components render" in the DevTools settings to see flashes around every component that renders.
Before optimizing, measure. Most context re-renders are cheap, and extra memoization adds code you have to maintain. Optimize when a profile shows a visible slowdown, for example a large list re-rendering on every keystroke.
Summary of the mental model
- A context change is a direct subscription update. It reaches consumers regardless of
memo. - The trigger is a different
valuebyObject.is. - Non-consumers re-render only through the usual parent-to-child rules.
- Consumers always take the whole value.
Exercise
In the first example, Static does not re-render when the count changes, but it is not wrapped in memo. What would you change so that Static does re-render on every click, and why does that change have this effect?
Show answer
Move <Static /> into the JSX returned by CountProvider itself, instead of passing it as children from App. Then CountProvider creates a new <Static /> element each time its state changes, and React re-renders it because it is a child of a component that re-rendered. When it arrived as children, the element was created by App, which did not re-render, so React reused the same element and skipped the work.
Exercise
A provider is written as <ThemeContext.Provider value={{ mode, toggle }}> inside a component that re-renders every second because of a clock in its parent. mode and toggle never change. Do consumers re-render each second? How do you stop it?
Show answer
Yes. The inline object is a new reference on every render, so Object.is reports a change and all consumers re-render. Create the object with useMemo(() => ({ mode, toggle }), [mode, toggle]), and make sure toggle is stable, for example by defining it with useCallback. The value keeps the same reference until mode changes.
Exercise
A component calls const { user } = useContext(AppContext) and AppContext holds { user, theme }. The theme changes. Does the component re-render, and does destructuring only user prevent it?
Show answer
It re-renders. The value object changed, and React tracks the context as a whole. Destructuring happens after the subscription is made, so it has no effect on whether the component renders.