Topic F4
Re-renders and memoization
Why one state change re-renders a whole subtree, and when memo helps.
Watch: one keystroke redraws every part of the page. With protection, parts that didn't change skip the redraw.
- moving now
- being checked
A render isn't a DOM change
A re-render means React runs the component function again and compares the result (previous topic). If the result is the same, the DOM isn't touched. So needless renders waste CPU time, not screen repaints. For small components that's microseconds. Trouble starts when hundreds of heavy components render on every keystroke.
Memoization for components
React.memo is memoization (Module 9) for components: remember the last render and reuse it when props are the same. "The same" means Object.is on each prop, a reference comparison. Objects, arrays and functions created fresh on every render are always different, so memo doesn't help unless you stabilise them.
Code, for programmersMemo that actually works
const Row = React.memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
function List({ items, query }) {
const visible = useMemo( // same array while inputs are equal
() => items.filter((i) => i.name.includes(query)), [items, query]);
const onSelect = useCallback((id) => select(id), []); // same function every render
return visible.map((item) => <Row key={item.id} item={item} onSelect={onSelect} />);
}
// without useCallback, onSelect is a new function each render and every Row re-renders anywayBefore reaching for memo
- Measure first with the React DevTools Profiler ("Highlight updates when components render"). Don't guess.
- Move state down: if only the search box needs the query, keep that state in the search box component, not in App. Nothing else re-renders.
- Lift content up: pass heavy components in as
children. Children are created by the parent, so they don't re-render when their wrapper's state changes. - The React Compiler (stable since 2025) adds memoization automatically at build time, so most hand-written useMemo and useCallback are no longer needed.
Quiz
App's state changes. Which components re-render (with no memo)?
<Row style={{ color: 'red' }} /> is wrapped in React.memo. Why does it still render every time?
The cheapest way to cut needless renders caused by query state in App?
0 of 3 answered.
Built on
Used in
No follow-up topics yet.