Sub topic 9
Memoizing the value you pass down
This chapter assumes you can create a context, wrap a subtree in a Provider, and read it with useContext. It also assumes you know that a state change re-renders a component and its children, and that you have used useMemo and useCallback at a basic level.
Why a fresh object causes extra renders
React decides whether a context changed by comparing the old and new value with Object.is. For objects, that compares identity, not contents. Two objects with the same fields are still different values.
This provider builds a new object on every render:
import { createContext, useState } from 'react';
export const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = (name) => setUser({ name });
const logout = () => setUser(null);
return (
<AuthContext.Provider value={{ user, login, logout }}>
{children}
</AuthContext.Provider>
);
}Suppose the parent of AuthProvider re-renders because of unrelated state. AuthProvider runs again, { user, login, logout } is a new object, and React re-renders every component that calls useContext(AuthContext). The user did not change, so this work is wasted.
Keep the value's identity stable
Wrap the object in useMemo so it is rebuilt only when its contents change. Wrap the functions in useCallback so they keep the same identity between renders.
import { createContext, useCallback, useMemo, useState } from 'react';
export const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState(null);
const login = useCallback((name) => setUser({ name }), []);
const logout = useCallback(() => setUser(null), []);
const value = useMemo(() => ({ user, login, logout }), [user, login, logout]);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
}Both steps are needed. If login were a plain function, it would be new on every render, the useMemo dependency array would change each time, and the memoization would do nothing. The callbacks here use setUser, which React guarantees is stable, so their dependency arrays can be empty.
What memoizing does and does not fix
| Situation | Value identity | Consumers re-render? |
|---|---|---|
| Provider's parent re-renders, value not memoized | New object | Yes |
| Provider's parent re-renders, value memoized | Same object | No |
| `user` state changes | New object, memoized or not | Yes |
Memoization only removes renders that have nothing to do with the data. When user really changes, every consumer of this context re-renders, including one that reads only login. To avoid that, split the context by concern, which a later chapter covers.
Checking that it works
To confirm the effect, add a console.log to a consumer component, then trigger a re-render of the provider's parent, for example with a counter in App. Without memoization the log appears on every click. With it, the log stays quiet until user changes. React DevTools Profiler shows the same thing under "Why did this render?"
Exercise
A provider passes value={{ theme, toggle }}, where toggle is defined inline in the component body. You wrap the object in useMemo(() => ({ theme, toggle }), [theme, toggle]), but consumers still re-render whenever the provider's parent re-renders. Why, and how do you fix it?
Show answer
toggle is a new function on every render, so the useMemo dependency toggle changes each time and the memo recomputes. Wrap toggle in useCallback with the right dependencies (for example [] if it only calls a state setter) so its identity stays stable. Then the memoized object keeps its identity and consumers are skipped.