Sub topic 13
Keeping, removing or adding manual memoization
This chapter assumes you know useMemo, useCallback, memo and useEffect, and that the compiler is already set up in your project. It covers what to do with memoization you wrote before the compiler existed, and when to write new memoization after it.
The default: leave existing code alone
The compiler understands useMemo, useCallback and memo. It keeps them and adds its own memoization around them. Existing code keeps working.
Removing manual memoization can change the compiled output. The compiler may memoize a value differently from how you did, so a component that behaved well before can re-render more or less often afterward. For that reason, leave existing calls in place unless you have a reason to remove them.
For new code, write plain components first and add memoization only when you can show a need for it.
import { useState } from 'react';
function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
}
export function List({ items }) {
const [query, setQuery] = useState('');
const [selectedId, setSelectedId] = useState(null);
const visible = items.filter((i) => i.name.includes(query));
const handleSelect = (id) => setSelectedId(id);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>Selected: {selectedId}</p>
<ul>
{visible.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}This is the same component as the hand-memoized version, without memo, useMemo or useCallback. When the compiler processes it, handleSelect and visible get stable references, so Row skips work when only selectedId changes.
When to keep manual memoization
Keep a manual call when it does a job the compiler cannot do for you.
| Situation | Why keep it |
|---|---|
| A memoized value is an effect dependency | `useMemo` or `useCallback` controls exactly when the effect fires. |
| A component was not compiled | A bailout means no automatic memoization, so your manual calls still matter. |
| Code runs under React 17 or 18 without the runtime | Output depends on your setup, so check it before removing anything. |
| You measured a cost | A profiled expensive computation with a known dependency list is worth pinning. |
The effect case is the most important. If an effect depends on a value, the compiler may memoize that value, but you cannot see or control when it changes. A manual useMemo or useCallback states the intent in code.
import { useCallback, useEffect } from 'react';
function Search({ query, onResults }) {
const run = useCallback(async () => {
const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`);
onResults(await res.json());
}, [query, onResults]);
useEffect(() => {
run();
}, [run]);
return null;
}Here run changes only when query or onResults changes, and the effect runs exactly then. Removing useCallback could change when the effect fires.
When to remove manual memoization
Removing is optional. It makes sense when you are already editing a component and the memoization adds noise. Follow this routine:
- Confirm the component is compiled, using React DevTools.
- Remove one memoization call, or a small group.
- Test the behavior, and profile if the call existed for performance.
- Revert the change if effects fire at different times or renders increase.
Do not remove calls across a whole codebase in one pass. Small changes make a regression easy to trace.
When to add memoization
Add manual memoization when the compiler cannot reach the code or cannot express what you need.
- A bailout. If the compiler skips a component, you can add
useMemooruseCallbackuntil you fix the underlying rule violation. - Effect control. Stabilize a dependency you do not want to trigger an effect.
- A measured hotspot. Wrap an expensive calculation after the profiler points at it.
The compiler only memoizes inside components and hooks it compiles. It does not make a slow function fast, and it does not fix an algorithm that does too much work.
A decision flow
Exercise
A compiled component uses useCallback to build a function that a useEffect lists as a dependency. A teammate wants to delete the useCallback to clean up the code. What do you advise, and why?
Show answer
Keep it, or remove it only after testing. The useCallback controls exactly when the effect runs. The compiler may memoize the function itself, but its choices are not visible in your code, so removing the call can change when the effect fires. If the team still wants to remove it, do it alone in one commit, confirm the component is compiled, and check that the effect fires the same number of times.
Exercise
A component shows Not compiled in React DevTools and scrolls slowly. Should you add useMemo and useCallback, fix the cause of the bailout, or both?
Show answer
Usually both, in order. Add manual memoization to relieve the slowness now, because the compiler is not helping this component. Then find why the compiler skipped it, for example a Rules of React violation reported by the lint rules, and fix it. After that, you can consider removing the manual calls.