Sub topic 12
Splitting contexts to limit re-renders
This chapter assumes you know useState, useReducer, createContext, useContext, and how a Provider's value triggers re-renders. It also assumes you have seen useMemo and useCallback. Here you will learn to divide one large context into several smaller ones, so a change in one piece of data does not re-render components that never read it.
Why one big context causes trouble
React compares a Provider's value with the previous one using Object.is. If the value changed, every component that called useContext for that context re-renders. React does not check which part of the value a component actually uses.
Suppose a single AppContext holds the current user, the theme, and a notification count. A component that only shows the theme still re-renders each time the notification count changes. The count lives in the same object, so the object is new, so every consumer is notified.
import { createContext, useContext, useMemo, useState } from 'react';
const AppContext = createContext(null);
export function AppProvider({ children }) {
const [user, setUser] = useState(null);
const [theme, setTheme] = useState('light');
const [unread, setUnread] = useState(0);
// One object holding unrelated data.
const value = useMemo(
() => ({ user, setUser, theme, setTheme, unread, setUnread }),
[user, theme, unread]
);
return <AppContext.Provider value={value}>{children}</AppContext.Provider>;
}
export function ThemeLabel() {
const { theme } = useContext(AppContext);
console.log('ThemeLabel rendered');
return <span>Theme: {theme}</span>;
}Memoizing the object does not help here. useMemo only prevents a new object when none of the dependencies changed. When unread changes, the dependency list changes too, so a new object is created and ThemeLabel renders again.
The component cannot opt out by selecting a field. useContext(AppContext) always subscribes to the whole value. Destructuring theme afterward changes nothing about the subscription.
The splitting principle
Give each context one reason to change. Two rules guide where to cut:
- Split by concern. Data that belongs to different features (authentication, theme, notifications) goes in different contexts.
- Split by update frequency. Data that changes often (a cursor position, a countdown, a notification count) should not share a context with data that rarely changes (the signed-in user, the locale).
A third split is the one you saw in the useReducer chapter: state and the functions that change it. A dispatch function from useReducer has a stable identity for the life of the component, so a context holding only dispatch never changes its value. Components that only send actions can then stay out of the render path when the state changes.
Splitting the example
Here is the same application with three contexts. Each provider owns one piece of state and memoizes its own value.
import { createContext, useContext, useMemo, useState } from 'react';
const UserContext = createContext(null);
const ThemeContext = createContext(null);
const NotificationsContext = createContext(null);
function useRequired(context, name, provider) {
const value = useContext(context);
if (value === null) {
throw new Error(`${name} must be used inside <${provider}>`);
}
return value;
}
export function UserProvider({ children }) {
const [user, setUser] = useState(null);
const value = useMemo(() => ({ user, setUser }), [user]);
return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
const value = useMemo(() => ({ theme, setTheme }), [theme]);
return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}
export function NotificationsProvider({ children }) {
const [unread, setUnread] = useState(0);
const value = useMemo(() => ({ unread, setUnread }), [unread]);
return (
<NotificationsContext.Provider value={value}>
{children}
</NotificationsContext.Provider>
);
}
export const useUser = () => useRequired(UserContext, 'useUser', 'UserProvider');
export const useTheme = () => useRequired(ThemeContext, 'useTheme', 'ThemeProvider');
export const useNotifications = () =>
useRequired(NotificationsContext, 'useNotifications', 'NotificationsProvider');
export function AppProviders({ children }) {
return (
<UserProvider>
<ThemeProvider>
<NotificationsProvider>{children}</NotificationsProvider>
</ThemeProvider>
</UserProvider>
);
}Now ThemeLabel calls useTheme() and ignores unread changes. The AppProviders component keeps the nesting out of your root component, which would otherwise grow a tall pyramid of Providers.
One detail matters here. When NotificationsProvider updates its own state, it re-renders, and so does its children subtree only if children is a new element. Because children is created by a parent that did not re-render, React reuses the same element and skips the subtree. Only components that read the context re-render. This is why Providers should receive children as a prop instead of rendering the tree inside themselves.
Separating state from actions
The reducer pattern gives a second kind of split. Keep the changing data in one context and the stable updater in another.
import { createContext, useContext, useReducer } from 'react';
const CounterStateContext = createContext(null);
const CounterDispatchContext = createContext(null);
function counterReducer(count, action) {
switch (action.type) {
case 'increment':
return count + 1;
case 'reset':
return 0;
default:
throw new Error('Unknown action: ' + action.type);
}
}
export function CounterProvider({ children }) {
const [count, dispatch] = useReducer(counterReducer, 0);
return (
<CounterStateContext.Provider value={count}>
<CounterDispatchContext.Provider value={dispatch}>
{children}
</CounterDispatchContext.Provider>
</CounterStateContext.Provider>
);
}
export function IncrementButton() {
const dispatch = useContext(CounterDispatchContext);
console.log('IncrementButton rendered');
return <button onClick={() => dispatch({ type: 'increment' })}>+1</button>;
}
export function CountDisplay() {
const count = useContext(CounterStateContext);
return <output>{count}</output>;
}When the count changes, CountDisplay re-renders because its context value changed. IncrementButton reads only the dispatch context, whose value is the same function as before, so it is not notified through context. Whether it re-renders for other reasons depends on its parent. If the parent re-renders and passes new props or is not memoized, the button renders anyway. Context splitting removes the context trigger and nothing else.
Verifying the effect
Do not guess whether a split helped. Check it.
- Add a
console.login the component body, as shown above, and trigger the update you care about. - Use the React DevTools Profiler with "Record why each component rendered" enabled. A re-render caused by context is listed as "Context changed".
- In development, React Strict Mode renders components twice. Count renders in the Profiler instead of the console, or you will see doubled logs.
Costs and limits of splitting
Splitting is not free. Weigh these points before you cut a context further.
| Concern | Effect |
|---|---|
| Number of Providers | More nesting. Fix it with a combined `AppProviders` component. |
| Related data in separate contexts | A component needing both must call two hooks, and updates to two contexts can render it twice in some cases. |
| Atomic updates | Two contexts updated in one event handler are batched by React, so a consumer of both still renders once. |
| Premature splitting | Many small contexts are harder to read. Split when you measure a problem or when the data clearly has different change rates. |
If a component truly needs only one field of a large, frequently changing object, splitting may not be enough. You then have three options:
- Push the expensive work into a child wrapped in
React.memo. The parent reads the context and passes the needed field as a prop. The memoized child skips rendering when that prop is unchanged. - Move the state out of context into an external store with selector subscriptions, which are covered in the next chapter on when context is the wrong tool.
- Restructure the tree so the changing state sits lower and fewer components are under it.
import { memo, useContext } from 'react';
import { ThemeContext } from './contexts';
function ExpensiveChart({ theme }) {
// Heavy rendering work here.
return <canvas data-theme={theme} />;
}
const MemoChart = memo(ExpensiveChart);
export function ChartContainer() {
const { theme } = useContext(ThemeContext);
return <MemoChart theme={theme} />;
}ChartContainer still re-renders when the context value changes, but MemoChart re-renders only when theme itself changes. Note that this works because theme is a string. Passing an object that is recreated each time defeats memo.
Common mistakes
- Splitting and then recombining. Building
{ user, theme }inside a component and passing it as a new Provider value brings back the original problem. - Forgetting that dispatch needs a stable identity.
dispatchfromuseReduceris stable. A function written inline in a component is not, so wrap it inuseCallbackbefore placing it in a context. - Expecting
memoto block context updates.React.memodoes not stop a component from re-rendering when a context it reads changes. It only compares props. - Putting the Provider too high. A Provider only needs to wrap the components that read it. A narrower Provider also keeps state local.
Exercise
A SettingsContext holds { language, fontSize, cursorPosition } in one memoized object. cursorPosition updates on every mouse move, and language and fontSize almost never change. A LanguagePicker component reads only language and re-renders constantly. How would you fix it, and why does memoizing the object not solve it?
Show answer
Move cursorPosition into its own context (or keep it as local state near the components that use it), and leave language and fontSize in a separate settings context. Memoizing the object does not help because cursorPosition is in the dependency list. Each mouse move creates a new object, Object.is reports a change, and every consumer of the context re-renders, including LanguagePicker, even though it uses only language.
Exercise
You split a counter into CounterStateContext and CounterDispatchContext. IncrementButton reads only the dispatch context but still logs a render each time the count changes. Give one likely cause and one fix.
Show answer
The parent of IncrementButton re-renders when the count changes, for example because the parent also reads the state context, and IncrementButton is not memoized, so it renders along with its parent. Wrap IncrementButton in React.memo (it takes no changing props), or restructure so the parent that reads the count does not render IncrementButton as part of its own output.