Sub topic 4
Skipping re-renders with React.memo
This chapter assumes you know function components and JSX, useState, how props and children are passed, and that JavaScript objects, arrays and functions are compared by reference. Earlier chapters covered why components re-render and how to measure that with the Profiler. Here you learn what React.memo does, what it compares, and where it fails.
What React.memo does
By default, when a component renders, React also renders every child component it returns. This happens even if the child received exactly the same props as last time. For most apps this is fast enough and needs no fix.
memo wraps a component and changes that rule. Before re-rendering the wrapped component, React compares its new props with the props from the last render. If every prop is the same, React skips the render and reuses the previous output.
import { memo } from 'react';
const Greeting = memo(function Greeting({ name }) {
console.log('render Greeting');
return <h1>Hello, {name}</h1>;
});memo takes a component and returns a new component. You use the result like the original. Naming the inner function, as above, keeps the component name readable in DevTools and in the Profiler.
How the comparison works
React compares props one by one, using Object.is on each prop. This is a shallow comparison. It checks whether each prop is the same value, not whether it has the same contents.
| Prop type | Compared how | Result |
|---|---|---|
| String, number, boolean | By value | `'a'` and `'a'` are the same |
| `null`, `undefined` | By value | Same if both are `null` |
| Object, array | By reference | `{}` and `{}` are different |
| Function | By reference | Two identical arrow functions are different |
| JSX element (such as `children`) | By reference | A new element is created on each parent render |
The last three rows cause most of the trouble with memo. Two objects with identical fields still count as changed if they are different objects in memory. The next chapter covers this in detail. For now, keep in mind that memo only helps when the props you pass are stable between renders.
A working example
The Row component below is wrapped in memo. The parent, List, keeps a selectedId in state. Selecting a row updates that state and re-renders List. Without memo, every Row would render again.
import { memo, useCallback, useState } from 'react';
const Row = memo(function Row({ item, onSelect }) {
console.log('render row', item.id);
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
export function List({ items }) {
const [selectedId, setSelectedId] = useState(null);
const handleSelect = useCallback((id) => {
setSelectedId(id);
}, []);
return (
<>
<p>Selected: {selectedId ?? 'none'}</p>
<ul>
{items.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}Two things make this work:
itemis an object that comes from theitemsarray. As long as the parent ofListpasses the same item objects, eachitemprop keeps its reference.handleSelectis wrapped inuseCallbackwith an empty dependency array, so it is the same function on every render.
If you remove useCallback, handleSelect becomes a new function on each render of List. Every Row then sees a changed onSelect prop, and memo has no effect. The console would log every row on every click. Both props must be stable for memo to skip anything.
To try it, render List from a small parent:
import { List } from './List';
const items = [
{ id: 1, name: 'Apples' },
{ id: 2, name: 'Bread' },
{ id: 3, name: 'Cheese' },
];
export default function App() {
return <List items={items} />;
}The items array is defined outside the component, so it is created once. On first load you see three render row logs. After that, clicking a row updates the Selected: line and logs nothing, because no Row received new props.
The Profiler shows the same thing. In a recorded commit, skipped components appear grey, with the note that they did not render. If you enable "Record why each component rendered" in the Profiler settings, it also lists which prop changed.
What happens during a render
The diagram shows what React decides for a memoized child when its parent renders.
The prop comparison only applies when the render is triggered by the parent. State inside the memoized component and context it reads are not blocked, which the next section covers.
What memo does not stop
memo only guards against re-renders caused by the parent. It does not stop these three triggers:
- Its own state. If the memoized component calls
setStateand the value changes, it re-renders.memohas no say in that. - Context it reads. If a component calls
useContextand the context value changes, it re-renders even when its props are identical. A later chapter covers this in detail. - A real prop change. If any compared prop is different, the render proceeds. That is the intended behavior.
Another point trips people up. memo does not prevent the render of the component's children by itself. If a memoized component renders, its non-memoized children render too. memo works at the boundary where you place it.
The children prop breaks memo
JSX that you pass as children is a prop like any other, and it is an object. Each time the parent renders, it creates new elements, so children is a new reference.
import { memo, useState } from 'react';
const Panel = memo(function Panel({ children }) {
console.log('render Panel');
return <section>{children}</section>;
});
export function Screen() {
const [count, setCount] = useState(0);
return (
<>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Panel>
<p>Static text</p>
</Panel>
</>
);
}Here Panel is wrapped in memo, but it still logs on every click. The <p>Static text</p> element is created again each time Screen renders, so children differs by reference. The same applies to inline objects, arrays and arrow functions written directly in the JSX.
You have three ways to handle it:
- Memoize the element with
useMemoso the reference stays stable. - Move the state out of
Screen, soScreendoes not re-render when the count changes. A later chapter covers this. - Accept the render if the component is cheap.
Option 2 is often the best, because it removes the problem rather than patching around it.
Where to place memo
Wrapping every component in memo is not a good plan. The comparison has a cost, and it only pays off when it skips real work. A component is a good candidate when all of these are true:
- It renders often, usually because its parent re-renders for unrelated reasons.
- Its props usually stay the same between those renders.
- Its render is expensive, or it sits at the top of a large subtree.
List rows, chart components and heavy form sections often fit. A small button or a label does not. Use the Profiler to find components that render often and take noticeable time, then add memo to those.
Wrapping a component that always receives new props is worse than not wrapping it. React still runs the comparison on every render, then renders anyway.
Verifying that memo works
Do not assume that memo is working just because you added it. Check with one of these methods:
- Add a temporary
console.login the component body, as in the examples, and watch whether it prints after an unrelated update. - Record a Profiler session, trigger the update, and look for a grey bar on the memoized component.
- Use "Record why each component rendered" to see which prop changed when it did render.
A console.log can mislead you in development with StrictMode. React deliberately renders components twice in development to expose side effects, so you may see doubled logs. The doubled log does not mean memo failed. Compare the count before and after your change, or rely on the Profiler.
If the component still renders, list its props and ask of each one: is this the same reference as last render? The culprit is almost always an inline object, array, function or JSX element created in the parent.
Common mistakes
- Memoizing the child but not the props.
memoplus an inlineonSelect={() => ...}gives you the comparison cost and no skipping. - Passing children into a memoized parent. As shown above, the
childrenelement is new on each parent render. - Mutating props or state. If you change an object in place and pass the same reference,
memosees no change and skips the render. The screen then shows stale data. Always create a new object or array when data changes. - Using memo as a correctness tool. Your component must work the same with or without
memo. React may discard cached results in some situations, so treatmemostrictly as an optimization.
Summary of the model
memoskips a render when the parent re-renders and every prop is equal byObject.is.- It does not block updates from the component's own state or from context.
- Objects, arrays, functions and JSX props are compared by reference, so they must be kept stable for
memoto help. - Add it where the Profiler shows frequent, costly, avoidable renders, and check that the skip actually happens.
Exercise
A memoized Row receives item (an object from state) and onSelect={() => select(item.id)} written inline in the parent. Clicking a button in the parent that changes unrelated state still logs a render for every Row. Why does memo not help, and what are two ways to fix it?
Show answer
The inline arrow function is a new function on every parent render, so onSelect fails the Object.is comparison and memo always sees a changed prop. One fix is to create the handler with useCallback in the parent and have Row call onSelect(item.id) itself, so the prop is stable. Another is to move the unrelated state out of the parent, for example into its own child component, so the parent no longer re-renders when that state changes.
Exercise
A component wrapped in memo still logs on every parent render, and its only prop is children, set to <p>Static text</p>. Why does it render, and what is one way to stop it?
Show answer
The JSX element is created again on each parent render, so children is a new object and fails the Object.is comparison. You can keep the element stable with useMemo, or move the changing state out of the parent so the parent does not re-render.