Sub topic 13
Keeping, removing or adding manual memoization
This chapter assumes you can read the compiler's setup and bailout behavior from the earlier chapters. You should also be comfortable with useMemo, useCallback, React.memo and the dependency array of useEffect. Here you will decide what to do with memoization you already have, and when to write new memoization in code the compiler handles.
The default position
The compiler memoizes components and hooks automatically. It works at a finer grain than most hand-written memoization, and it can memoize code after an early return, which hooks cannot do. For new code, start with no useMemo, useCallback or React.memo. Add them only when you have a specific reason.
For existing code, the default is the opposite: leave the memoization where it is. Removal is optional, and it carries some risk.
Keeping existing memoization
Existing useMemo, useCallback and memo calls are safe to leave. They do three things for you.
- They preserve behavior you already tested. The compiler's output can differ from your hand-written memoization. A value you memoized may be cached at a different boundary after the compiler runs. Most of the time the difference is invisible, but an effect that depends on that value can fire a different number of times.
- They give the compiler information. The compiler tries to preserve the memoization you wrote. If it cannot prove that its output keeps the same guarantees, it skips the component rather than risk a behavior change. Your manual calls are therefore constraints the compiler checks.
- They cost nothing to keep. The compiler tolerates them. The only price is some extra code to read.
The first row of the following table shows the pattern most teams hit. The rest summarize the cases that follow.
| Situation | Recommendation |
|---|---|
| Existing `useMemo` or `useCallback` that works | Keep it |
| Existing memoization that makes the compiler skip the component | Fix the code, or remove the memoization after testing |
| New component with no special needs | Write no manual memoization |
| Value used as an `useEffect` dependency | Keep or add memoization if the effect must not re-run |
| Expensive pure function shared by many components | Memoize outside React, in a module-level cache |
Removing memoization safely
Removing manual memoization makes code shorter, but the compiler's output changes as a result. Treat each removal as a behavior change that you verify.
Here is a reasonable process.
- Confirm the component is compiled. Check for the memo badge in React DevTools, as described in the verification chapter.
- Remove the manual calls in a small, separate change. Do not mix this with a feature.
- Run your tests and exercise the component by hand. Pay attention to effects, timers, subscriptions and anything that talks to the network.
- Profile if the original memoization was added for a performance reason. Compare render counts before and after.
- If something regresses, restore the memoization. Do not spend time diagnosing it unless the code is hot.
The earlier chapter showed the same list component written two ways. The memoized version with memo, useMemo and useCallback and the plain version should behave the same once compiled. Removing the wrappers is a good first candidate. It has no effects and the values are only passed to children.
Do not remove memoization from a component the compiler skips. The compiler is not running on it, so the plain version loses the protection that the manual calls provided. Check the bailout first, then decide.
Effect dependencies: the main reason to keep `useMemo` and `useCallback`
An effect re-runs when any dependency changes by Object.is comparison. If you build an object or function during render and pass it to the dependency array, you need it to keep the same identity between renders when its inputs have not changed.
The compiler memoizes values, so it often provides that stability. It does not promise the exact set of renders where an identity stays the same. If an effect would cause a harmful side effect when it runs one extra time, such as reconnecting a socket, make the memoization explicit.
import { useEffect, useMemo } from 'react';
function createConnection({ serverUrl, roomId }) {
return {
connect() {
console.log(`Connecting to ${roomId} at ${serverUrl}`);
},
disconnect() {
console.log(`Disconnected from ${roomId}`);
},
};
}
export function ChatRoom({ roomId, serverUrl }) {
// Explicit memoization: the effect below must run only when
// roomId or serverUrl changes, not on every render.
const options = useMemo(
() => ({ roomId, serverUrl }),
[roomId, serverUrl]
);
useEffect(() => {
const connection = createConnection(options);
connection.connect();
return () => connection.disconnect();
}, [options]);
return <h1>Room: {roomId}</h1>;
}A cleaner alternative is to move the object creation inside the effect and depend on the primitive values.
import { useEffect } from 'react';
function createConnection({ serverUrl, roomId }) {
return {
connect() {
console.log(`Connecting to ${roomId} at ${serverUrl}`);
},
disconnect() {
console.log(`Disconnected from ${roomId}`);
},
};
}
export function ChatRoom({ roomId, serverUrl }) {
useEffect(() => {
const connection = createConnection({ roomId, serverUrl });
connection.connect();
return () => connection.disconnect();
}, [roomId, serverUrl]);
return <h1>Room: {roomId}</h1>;
}The second version does not depend on any memoization, compiled or manual. It is robust under any compiler setting, so prefer it when the code allows it. Use useMemo or useCallback when the value must be shared between the effect and the render output, or when it is passed through several layers.
Adding memoization on purpose
Sometimes you will write new useMemo or useCallback calls in a compiled codebase. The valid reasons are narrow.
- Effect dependency control, as above.
- Precise control over identity for a value that you pass to a third-party library which compares by reference, such as a charting or map component that rebuilds its internal state when an option object changes.
- A calculation the compiler cannot reach. The compiler only analyzes components and hooks. A pure function that you call inside a component is memoized as part of the component's output, but the compiler does not memoize the function in other contexts.
Memoization the compiler creates is per component instance. If a hundred rows each call the same expensive pure function with the same input, each row computes it once. The compiler does not share results between instances. For that case, use a module-level cache outside React.
// log-parser.js
const cache = new Map();
export function parseLog(text) {
if (cache.has(text)) {
return cache.get(text);
}
const lines = text
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
cache.set(text, lines);
return lines;
}This cache grows without bound, so for real data add an eviction policy, or key it on something with a limited range. Because the function is pure and lives outside React, the compiler and React DevTools are not involved. Components that call it follow the usual rules.
When memoization blocks the compiler
The compiler checks that its output preserves the guarantees of your existing useMemo and useCallback calls. A common failure is a dependency array that does not match what the callback actually reads. For example, the callback reads filter, but the array lists only items. The old code ran, with a stale value. The compiler cannot reproduce that behavior in a safe way, so it skips the component.
Fix it by making the array accurate, or remove the manual call. The exhaustive-deps rule flags this pattern, so listen to it before you adopt the compiler widely.
import { useMemo } from 'react';
// Before: the callback reads `filter`, but the array omits it.
function Before({ items, filter }) {
const shown = useMemo(
() => items.filter((item) => item.kind === filter),
[items]
);
return <p>{shown.length} items</p>;
}
// After: dependencies match what the callback reads.
function After({ items, filter }) {
const shown = useMemo(
() => items.filter((item) => item.kind === filter),
[items, filter]
);
return <p>{shown.length} items</p>;
}The After version also changes behavior: it now updates when filter changes. This is the correct behavior, but it is a visible change, so test it.
You can also opt a single component out while you work through its memoization with the 'use no memo' directive. Use it as a temporary measure and leave a comment with the reason.
function LegacyPanel({ model }) {
'use no memo';
// TODO: remove after the manual memoization below is cleaned up.
return <span>{model.label}</span>;
}Common mistakes
- Removing all memoization in one sweep. You get a large diff with no way to find which removal caused a regression.
- Removing memoization in components that are not compiled. Check the compilation mode and the bailouts first.
- Assuming the compiler memoizes everything. It does not touch values outside components and hooks, and it does not share work across component instances.
- Disabling the hooks lint rule. The compiler needs accurate dependencies as much as the old approach did.
- Adding
useMemo"just in case". Without a stated reason, it is noise that the next reader must evaluate.
Exercise
A component builds const config = { id, mode } during render and passes config in the dependency array of a useEffect that opens a network connection. Compiled output sometimes re-runs the effect more often than you want. Name two ways to fix this and say which you prefer.
Show answer
Option 1: wrap the object in useMemo(() => ({ id, mode }), [id, mode]) so the identity is stable by your own contract. Option 2: create the object inside the effect and list the primitives id and mode in the dependency array. Prefer option 2, because it does not rely on any memoization, manual or compiled, and the dependencies are plain values.
Exercise
You remove a useCallback from a component, and the component then shows no memo badge in React DevTools. What does this suggest, and what do you do next?
Show answer
The compiler likely skips the component, either because of a Rules of React violation or an earlier bailout, so removing the manual memoization removed the only protection. Check the ESLint diagnostics and the compiler's bailout report, fix the violation, and confirm the badge appears. If you cannot fix it quickly, restore the useCallback.