Sub topic 14
How props relate to re-rendering and memo
This chapter assumes you can write function components, pass props, and use useState. It also assumes you know that a callback prop is a function passed down from a parent. It covers when a component re-renders, what changes in its props can and cannot prevent, and how memo compares props.
What a re-render is
A render is React calling your component function to get its JSX. A re-render is the same call made again, because something changed. React then compares the new JSX with the previous output and updates the DOM only where they differ.
A re-render does not mean the browser repaints everything. Calling a function and building a small tree of objects is cheap. Re-rendering becomes a problem only when a component is expensive to render or when thousands of them render at once.
A component re-renders for three reasons:
- Its own state changes.
- A context value it reads changes.
- Its parent re-renders.
The third reason is the one that matters for props. By default, React does not check whether a child's props changed. If the parent re-renders, every child it returns re-renders too, even with identical props.
A child re-renders even when its props are the same
import { useState } from 'react';
function Price({ amount }) {
console.log('Price rendered');
return <p>${amount}</p>;
}
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<Price amount={20} />
</div>
);
}Each click updates count in App, so App re-renders. Price receives amount={20} every time, but React still calls it, and the console logs Price rendered on every click.
Props are therefore not a trigger for rendering. They are inputs that a component receives when React renders it. A change in props only matters when the parent re-renders and passes different values.
The diagram below shows the default flow and the flow with memo.
Skipping work with memo
memo wraps a component so that React skips re-rendering it when its props are the same as last time.
import { memo } from 'react';
const Row = memo(function Row({ item }) {
return <li>{item.name}</li>;
});React compares the old and new props one by one with Object.is. This is a shallow comparison. It checks whether each prop is the same value, not whether two objects have the same contents.
| Prop type | Comparison result |
|---|---|
| Strings, numbers, booleans | Equal when the values match |
| `null` and `undefined` | Equal to themselves |
| Objects, arrays, functions | Equal only when they are the same reference |
Two objects with identical fields are still different values:
const a = { name: 'Ada' };
const b = { name: 'Ada' };
console.log(Object.is(a, b)); // false
console.log(Object.is(a, a)); // trueThis is the most common reason memo appears to do nothing.
Why memo often fails: new references on every render
Every time a component function runs, expressions inside it create new values. An object literal, an array literal, or an arrow function written in JSX is a new reference on each render.
import { memo, useState } from 'react';
const Toolbar = memo(function Toolbar({ options, onSave }) {
console.log('Toolbar rendered');
return <button onClick={onSave}>Save ({options.theme})</button>;
});
export default function Editor() {
const [text, setText] = useState('');
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<Toolbar
options={{ theme: 'dark' }}
onSave={() => console.log('saved', text)}
/>
</div>
);
}Toolbar is memoized, but it re-renders on every keystroke. options is a new object and onSave is a new function each time Editor runs, so Object.is reports a difference for both props.
There are three ways to keep references stable:
- Move values that never change outside the component.
- Use
useMemofor objects and arrays computed from other values. - Use
useCallbackfor functions.
import { memo, useCallback, useState } from 'react';
const OPTIONS = { theme: 'dark' };
const Toolbar = memo(function Toolbar({ options, onSave }) {
console.log('Toolbar rendered');
return <button onClick={onSave}>Save ({options.theme})</button>;
});
export default function Editor() {
const [text, setText] = useState('');
const handleSave = useCallback(() => {
console.log('saved', text);
}, [text]);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<Toolbar options={OPTIONS} onSave={handleSave} />
</div>
);
}OPTIONS is created once at module load. handleSave depends on text, so it still changes on each keystroke, and Toolbar still re-renders. To make the callback stable, read the latest text another way. For example, give Toolbar a callback that takes the value as an argument, or keep the text in a ref. A stable callback is only worth the effort if the child is expensive to render.
The children prop is also a new value
The children prop is an ordinary prop, and JSX creates a new element object on each render. A memoized component that receives JSX children will therefore re-render whenever its parent does.
import { memo, useState } from 'react';
const Panel = memo(function Panel({ children }) {
console.log('Panel rendered');
return <section>{children}</section>;
});
export default function Page() {
const [open, setOpen] = useState(false);
return (
<div>
<button onClick={() => setOpen(!open)}>Toggle</button>
<Panel>
<p>Static text</p>
</Panel>
</div>
);
}Here <p>Static text</p> is rebuilt on every Page render, so memo on Panel never helps. The same applies to slot props such as header={<h1>Dashboard</h1>}.
A cleaner fix is often to change where the state lives. If only the toggle needs open, move the button and its state into their own component. Page then never re-renders when the state changes, and nothing below it is affected.
What memo does not block
memo only compares props. A memoized component still re-renders when:
- Its own state changes.
- A context it reads through
useContextchanges. This ignores props completely.
A memoized child also stays in sync only if props are treated as immutable. Suppose a parent mutates an object and passes the same reference:
function addTag(item) {
item.tags.push('new'); // mutates the existing object
setItem(item); // same reference, so React and memo see no change
}useState bails out because the reference is unchanged, and memo skips the child. The screen does not update. This is a practical reason props and state should be treated as read-only. Create a new object instead:
function addTag(item) {
setItem({ ...item, tags: [...item.tags, 'new'] });
}Custom comparison
memo accepts a second argument, a function that receives the previous and next props and returns true if the component can skip rendering.
import { memo } from 'react';
const Chart = memo(
function Chart({ data, title }) {
return <figure>{title}: {data.length} points</figure>;
},
(prev, next) => prev.title === next.title && prev.data.length === next.data.length
);Use this rarely. The comparison above ignores changes to values inside data, which can show stale output. If you write a custom comparison, compare every prop, including functions. A function prop you skip may close over old state. Deep equality checks on large data can cost more than the render they avoid.
When to use memo
- Render first without it. Most components are fast enough.
- Measure with the React DevTools Profiler. Look for components that render often with unchanged props and take noticeable time.
- Prefer structural fixes: move state down, or pass expensive elements as
childrenfrom a parent that does not re-render. - Add
memoand stable references together. One without the other has no effect.
The React Compiler, if your project enables it, adds this kind of memoization automatically. The reasoning in this chapter still applies, because it explains what the compiler is doing.
Exercise
A parent holds a count state. It renders <Chart config={{ color: 'red' }} />, and Chart is wrapped in memo. Clicking a button that increments count still re-renders Chart. Explain why, and give two ways to fix it.
Show answer
The object literal { color: 'red' } is a new reference on every parent render, so the shallow Object.is comparison sees config as changed. Fix it by moving the object outside the component (const CONFIG = { color: 'red' };) and passing config={CONFIG}, or by creating it with useMemo(() => ({ color: 'red' }), []) inside the component. Passing the primitive value instead (color="red") also works.
Exercise
A memoized Panel receives <p>Static text</p> as its children, and Panel re-renders each time its parent does. Why, and what restructuring avoids the problem without useMemo?
Show answer
JSX creates a new element object on each parent render, so the children prop is a new reference and memo sees a change. Moving the changing state into a smaller component, so the parent that creates the children does not re-render, avoids the problem.