Sub topic 9
Memoizing the value you pass down
This chapter assumes you know createContext, Provider and useContext, and that you can share state through a provider. It also assumes you know that a component re-renders when its state, props or parent change. You should have seen useMemo and useCallback before.
Why the value's identity matters
React decides whether context changed by comparing the old and new value props with Object.is. For primitives such as strings, numbers and booleans, this compares by content. For objects, arrays and functions, it compares by reference.
Every time a function component runs, an object literal creates a new object. If a provider writes value={{ user, login }}, each render of the provider produces a new object, even when user and login are unchanged. React sees a different reference and re-renders every component that calls useContext for that context.
That cost is invisible in a small app. It becomes noticeable when many consumers sit below a provider that re-renders often.
Seeing the problem
This provider holds a counter and also a text field with its own state. The value object is built inline.
import { createContext, useContext, useState } from 'react';
const CounterContext = createContext(null);
export function CounterProvider({ children }) {
const [count, setCount] = useState(0);
const [note, setNote] = useState('');
const value = {
count,
increment: () => setCount((c) => c + 1),
};
return (
<CounterContext.Provider value={value}>
<input value={note} onChange={(e) => setNote(e.target.value)} />
<button onClick={value.increment}>Add</button>
{children}
</CounterContext.Provider>
);
}
export function CountDisplay() {
const { count } = useContext(CounterContext);
console.log('CountDisplay rendered');
return <p>Count: {count}</p>;
}
export default function App() {
return (
<CounterProvider>
<CountDisplay />
</CounterProvider>
);
}Type in the input and watch the console. CountDisplay rendered is logged on every keystroke, although count never changed. Typing updates note, which re-renders CounterProvider. That builds a new value object, and React re-renders every consumer.
The children prop is not the cause. App did not re-render, so the <CountDisplay /> element is the same object as before, and React skips it as an ordinary child. The context change is what forces CountDisplay to render.
Fixing it with useMemo and useCallback
The goal is to give React the same value reference whenever its contents are unchanged. Two hooks cover this:
useMemocaches the object and rebuilds it only when a dependency changes.useCallbackcaches each function placed inside it. Without that, a new function on every render would make the memoized object change anyway.
import { createContext, useCallback, useContext, useMemo, useState } from 'react';
const CounterContext = createContext(null);
export function CounterProvider({ children }) {
const [count, setCount] = useState(0);
const [note, setNote] = useState('');
const increment = useCallback(() => setCount((c) => c + 1), []);
const value = useMemo(() => ({ count, increment }), [count, increment]);
return (
<CounterContext.Provider value={value}>
<input value={note} onChange={(e) => setNote(e.target.value)} />
<button onClick={increment}>Add</button>
{children}
</CounterContext.Provider>
);
}
export function CountDisplay() {
const { count } = useContext(CounterContext);
console.log('CountDisplay rendered');
return <p>Count: {count}</p>;
}
export default function App() {
return (
<CounterProvider>
<CountDisplay />
</CounterProvider>
);
}Now typing in the input re-renders CounterProvider, but useMemo returns the cached object because count and increment are unchanged. Object.is reports the same reference, and CountDisplay is not re-rendered. Clicking Add changes count, which rebuilds the object, so CountDisplay correctly renders again.
Two details make this work:
incrementuses the updater formsetCount((c) => c + 1). It does not readcount, so the callback has an empty dependency list and stays stable.- Every value the memoized object contains appears in the
useMemodependency array. Leave one out and consumers may see stale data.
The decision flow
When memoizing helps and when it does not
Memoization only prevents re-renders caused by the provider re-rendering for reasons unrelated to the context's contents. Typical causes are:
- The provider's parent re-renders and passes new props or children.
- The provider holds other state, as
notedid above. - The provider reads a second context or hook that updates.
It does not help when the data itself changed. If count changes, a new value is correct, and every consumer re-renders, including ones that read only increment. Avoiding that requires splitting the context, which a later chapter covers.
| What you pass as `value` | Memoize? | Reason |
|---|---|---|
| A string, number or boolean | No | `Object.is` compares by content. |
| A `useState` value that is an object or array | No | The reference changes only when you call the setter. |
| An object literal like `{ user, login }` | Yes | New reference on every provider render. |
| A function defined in the provider body | Yes, with `useCallback` | New function on every render. |
| `dispatch` from `useReducer` | No | React guarantees it is stable. |
| `setState` from `useState` | No | React guarantees it is stable. |
Common mistakes
- Memoizing the object but not the functions. If
loginis recreated each render and appears in the dependency array,useMemorebuilds every time. The memoization does nothing. - Omitting dependencies.
useMemo(() => ({ user, login }), [])freezesuserat its first value. Consumers never see updates. Thereact-hooks/exhaustive-depslint rule catches this. - Mutating the value.
value.count++followed by re-providing the same object leaves the reference unchanged, so React skips the update. Always create new objects through state setters. - Memoizing everything by default.
useMemohas its own cost and adds code to read. Apply it to context values that feed many consumers or expensive subtrees, and measure first with the React DevTools Profiler when you are unsure. - Expecting
React.memoon a consumer to block context updates. A memoized component still re-renders when a context it reads changes.React.memoonly blocks re-renders from props and parent renders.
Checking your work
A quick way to verify a provider is well memoized is to add a temporary effect in a consumer and trigger an unrelated provider update.
import { useEffect, useRef } from 'react';
export function useRenderCount(label) {
const count = useRef(0);
count.current += 1;
useEffect(() => {
console.log(`${label}: render #${count.current}`);
});
}Call useRenderCount('CountDisplay') inside CountDisplay. Type in the note field and confirm the render number stays the same. Then click Add and confirm it goes up by one. Remove the hook once you are satisfied.
Exercise
A provider is written as const value = useMemo(() => ({ user, logout }), [user]); where logout is declared in the provider body as const logout = () => setUser(null);. The linter warns about a missing dependency. What is the bug, and how do you fix it?
Show answer
logout is created fresh on every render, so a consumer that calls it gets whichever copy was captured when useMemo last ran. Here that copy still works, because setUser is stable, but the code breaks as soon as logout reads other state. Adding logout to the dependency array would fix staleness but would rebuild the object on every render, because logout is a new function each time. The fix is to wrap it: const logout = useCallback(() => setUser(null), []); and use [user, logout] as the dependencies. Now logout is stable and the object changes only when user does.
Exercise
A provider holds const [theme, setTheme] = useState('light'); and renders <ThemeContext.Provider value={theme}>. Its parent re-renders often. Do consumers re-render each time, and does adding useMemo change anything?
Show answer
Consumers do not re-render because of the parent. theme is a string, and Object.is('light', 'light') is true, so React sees no context change. Wrapping a primitive in useMemo adds code without changing behavior. Memoization matters only when the value is an object, array or function created during render.