Sub topic 8
Why the child must be memoized
This chapter assumes you know function components, useState, props, and how React re-renders a component tree. You should also have seen useDeferredValue at a basic level. Familiarity with React.memo helps, but the chapter explains what you need.
The problem: a deferred value alone does not make anything faster
useDeferredValue returns a value that lags behind the real one. When query changes, React first re-renders with the old value in deferredQuery. Then it starts a second, background render with the new value. That second render can be interrupted if the user types again.
The first render, the one that keeps the old value, is the part people forget about. React still has to run it. If the slow component re-renders during that first pass, you pay the full cost of the slow render on every keystroke, and typing feels just as slow as before.
Consider this version, which defers the value but does not memoize the child.
import { useState, useDeferredValue } from 'react';
function SlowList({ query, items }) {
const visible = items.filter((item) => item.includes(query));
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
}
function App({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<SlowList query={deferredQuery} items={items} />
</>
);
}SlowList is a plain function component. Whenever App re-renders, React re-renders SlowList too, because a parent render re-renders its children by default. The props may be identical, but React does not check that unless you ask it to.
Follow one keystroke:
- The user types "a".
setQuery('a')is an urgent update. - React re-renders
App.queryis'a', butdeferredQueryis still''. Appreturns<SlowList query="" ... />. SinceSlowListis not memoized, React renders it again with the same props. This is the slow part, and it blocks the urgent render.- React then starts a background render with
deferredQueryequal to'a'.
Step 3 does useless work. The input cannot update until it finishes. The deferral moved the real work to the background but left a full copy of the slow work in the urgent path.
What `memo` changes
React.memo wraps a component so that React compares the new props with the previous props before rendering it. If every prop is equal, React skips the render and reuses the last result.
import { useState, useDeferredValue, memo } from 'react';
const SlowList = memo(function SlowList({ query, items }) {
const visible = items.filter((item) => item.includes(query));
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});
function App({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const isStale = query !== deferredQuery;
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<div style={{ opacity: isStale ? 0.6 : 1 }}>
<SlowList query={deferredQuery} items={items} />
</div>
</>
);
}Now the same keystroke goes differently:
- The user types "a".
setQuery('a')is urgent. - React re-renders
Appwithquery = 'a'anddeferredQuery = ''. SlowListreceivesquery=""and the sameitemsas last time.memosees equal props and skips it. The urgent render is cheap, and the input updates at once.- React starts the background render with
deferredQuery = 'a'. The props now differ, soSlowListrenders. If the user types again, React abandons this render and starts over with the newer value.
The memo wrapper is what makes the deferral pay off. The two features work as a pair.
Why the background render is a separate pass
It helps to know what React does internally. During the urgent render, useDeferredValue returns the previous value. It also schedules a second render at a lower priority, with the new value. React can pause that low-priority render, yield to the browser, and drop it if a newer urgent update arrives.
This explains two details:
- The urgent render and the background render are separate passes through your component.
memoonly helps the first one, which is what you want, because the first one must be fast. - If the background render is interrupted and restarted, the work it did is discarded. A slow child that renders in the background costs CPU time, but it never freezes the input.
Props must stay referentially equal
memo uses shallow comparison. For each prop, React checks whether the old and new values are the same according to Object.is. Strings and numbers compare by value. Objects, arrays, and functions compare by identity.
So a prop that is recreated on every render defeats memo, even when its contents are the same. In the urgent render of the memoized example, items comes from props and does not change, and deferredQuery is a string that has not changed. Both are equal, so memo works.
Now suppose App computed an object or callback inline.
function App({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<SlowList
query={deferredQuery}
items={items}
options={{ caseSensitive: false }}
onPick={(item) => console.log(item)}
/>
</>
);
}The options object and the onPick function are new on every render of App. memo sees different identities and re-renders SlowList in the urgent pass. The deferral gives you nothing.
You have three ways to fix this:
- Move constant values outside the component, so they are created once.
- Wrap objects in
useMemoand callbacks inuseCallback, with correct dependency arrays. - Pass primitives instead of objects when you can, for example
caseSensitive={false}.
import { useState, useDeferredValue, useCallback, useMemo } from 'react';
function App({ items }) {
const [query, setQuery] = useState('');
const deferredQuery = useDeferredValue(query);
const options = useMemo(() => ({ caseSensitive: false }), []);
const onPick = useCallback((item) => console.log(item), []);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<SlowList
query={deferredQuery}
items={items}
options={options}
onPick={onPick}
/>
</>
);
}This assumes SlowList is the memoized component from the earlier example, extended to accept options and onPick.
Checking whether the child is skipped
Do not assume memo is working. Verify it.
One way is the React DevTools Profiler. Record a keystroke and look at the flame graph. A component skipped by memo shows as gray, with the note "Did not render". If SlowList shows a render time in the first commit, something in its props changed.
A second way is a temporary log inside the component.
const SlowList = memo(function SlowList({ query, items }) {
console.log('SlowList render, query =', JSON.stringify(query));
const visible = items.filter((item) => item.includes(query));
return (
<ul>
{visible.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
);
});When working correctly, each keystroke logs the old query only if a render happens at all, and the new query appears once, from the background render. If you see the old query logged on every keystroke, the child is rendering in the urgent pass.
In development with Strict Mode, React renders components twice on purpose, so expect doubled logs. Compare against the same code without memo to see the difference.
Common mistakes
| Mistake | What happens | Fix |
|---|---|---|
| Deferring a value but not memoizing the child | The slow child renders in the urgent pass, so typing is still slow | Wrap the child in `memo` |
| Passing a new object or function prop each render | `memo` sees a changed prop and re-renders the child | Use `useMemo`, `useCallback`, or move the value out |
| Passing both `query` and `deferredQuery` to the child | The urgent prop changes on every keystroke | Pass only the deferred value |
| Memoizing the parent instead of the slow child | The parent still re-renders because its own state changed | Memoize the component that does the slow work |
| Slow work happening in `App` itself | `memo` cannot skip code that runs in the component that owns the state | Move the slow work into a memoized child |
The last row matters. useDeferredValue defers a value, not a computation. If App itself runs the expensive filter inline, that work runs in the urgent render regardless of memo. Extract it into a child component, as SlowList does.
When memoization is not enough
Skipping the urgent render solves the main problem. The background render can still be slow, and a very slow one is still wasteful. If the background render takes seconds, the list will feel stale for a long time even though typing stays smooth. In that case, consider reducing the work itself, for example by virtualizing the list so it renders only visible rows, or by computing the filtered data with useMemo in a better data structure.
Also remember that memo is an optimization with a cost. Each memoized component pays for a props comparison on every parent render. Apply it to the component that is actually slow, not to every component in the tree.
Exercise
A developer wrote const deferred = useDeferredValue(text); and renders <Report text={deferred} />, but typing in the input is still laggy. Report is a plain function component that takes about 200 ms to render. What is wrong, and what is the fix?
Show answer
Because Report is not memoized, it re-renders during the urgent pass with the old deferred value (parent renders re-render children by default), costing 200 ms before the input can update. Wrap it in memo, for example const Report = memo(function Report({ text }) { ... }). Then React skips it in the urgent render because text is unchanged, and renders it only in the background render with the new value.
Exercise
After adding memo to SlowList, the Profiler still shows it rendering on every keystroke. The parent passes <SlowList query={deferredQuery} items={items} onPick={(i) => select(i)} />. Why, and how do you fix it?
Show answer
The inline arrow function onPick is a new function on every render of the parent, so the shallow props comparison finds a changed prop and memo does not skip the render. Fix it by wrapping the handler in useCallback with correct dependencies (for example useCallback((i) => select(i), [select])) or by otherwise keeping its identity stable.