Explain it simply
Explain it simply
Whenever state changes, React calls your component functions again to work out the new UI. That is a re-render, and it is usually so fast you never notice. Problems appear only when a component repeats heavy work on every render.
When you take a wrong turn while driving, you check the map instead of turning left and right at random. Performance work is the same, and the Profiler is the map. Fix things only after you see which component takes how long.
Problem → Why → Solution
The problem: a list that is slow even with memo
A list of 5,000 products lags every time the user types in the search box. The developer wraps ProductRow in memo, but nothing improves. Opening the Profiler shows that every row still re-renders on every keystroke.
The cause is style={{ padding: 8 }} and onSelect={() => ...}. Each parent render creates a new object and a new function, so memo sees changed props. The filter also runs over all 5,000 items on every keystroke.
const ProductRow = memo(function ProductRow({ product, style, onSelect }) {
return <li style={style} onClick={onSelect}>{product.name}</li>;
});
function ProductList({ products, onPick }) {
const [query, setQuery] = useState('');
const visible = products.filter((p) => p.name.includes(query));
return visible.map((p) => (
<ProductRow key={p.id} product={p}
style={{ padding: 8 }} // new object every render
onSelect={() => onPick(p.id)} /> // new function every render
));
}Why doesn't memo help?
memo compares each prop with Object.is. Strings and numbers count as equal when their values match, but objects and functions are equal only when they are the same reference. Two { padding: 8 } objects look alike yet are different objects, so memo never skips. Adding memo alone is not enough.
Core concept: measure, restructure, then memoize
A component re-renders for three reasons: its own state changed, its parent re-rendered, or a context value it reads changed. A re-render is not a DOM rewrite. React compares the result and updates only the parts of the DOM that really changed, so most re-renders are harmless. Work in this order.
1. Measure first
Record in the Profiler tab of React DevTools and perform the slow interaction. The flamegraph shows how long each component took. Development builds are slower, so confirm exact numbers with a production build.
2. Fix the structure first
Move state down to the component that needs it, so a large parent stops re-rendering. Virtualize long lists so only visible rows render. Use stable keys. These changes often help more than memo.
3. Then memoize
memo skips a component whose props did not change. useMemo reuses a calculated result or object until its dependencies change. useCallback keeps a function reference stable. The last two matter mostly for props passed to memo children.
| Tool | What it caches | Pays off when |
|---|---|---|
| memo(Component) | The whole render result | A slow child often rendered with the same props |
| useMemo(fn, deps) | fn's return value | Heavy calculations, objects passed to memo children |
| useCallback(fn, deps) | fn itself | Event handlers passed to memo children |
React Compiler
React Compiler is a build-time tool that adds this memoization automatically to components and hooks that follow the Rules of React. The React team has announced a stable 1.0 release (see the reference link). With the compiler on, new code needs far fewer hand-written memo, useMemo and useCallback calls, but the habit of measuring stays the same.
- Record with the Profiler
- Find the slowest component
- Fix state placement and structure
- Memoize only if still needed
Record again after every change. If the numbers did not improve, remove the memoization you added; it only made the code harder to read.
General pattern
const Child = memo(function Child({ items, onAction }) { /* ... */ });
function Parent({ source, filter }) {
const items = useMemo(() => expensiveWork(source, filter), [source, filter]);
const onAction = useCallback((id) => doSomething(id), []);
return <Child items={items} onAction={onAction} />;
}Only when the object passed to a memo child is stable through useMemo, and the function through useCallback, can memo's comparison conclude that nothing changed.
Skipping list items with memo
In the App below, every click changes the count state, so App re-renders. LessonItem is wrapped in memo and receives only a string title, so React skips it while the title stays the same. Watching when console.log fires lets you see the skip happen.
import { memo, useState } from 'react';
const LessonItem = memo(function LessonItem({ title }) {
console.log('render lesson:', title);
return <li>{title}</li>;
});
function App() {
const [count, setCount] = useState(0);
const lessons = ['JSX', 'Props', 'State'];
return (
<div>
<button onClick={() => setCount(count + 1)}>Clicked {count}</button>
<ul>
{lessons.map(lesson => (
<LessonItem key={lesson} title={lesson} />
))}
</ul>
</div>
);
}Code breakdown
- Wrap the child in memo
const LessonItem = memo(function LessonItem({ title }) {memo wraps the component and compares the new props with the previous ones using Object.is. If all match, it reuses the previous result.
- A probe for renders
console.log('render lesson:', title);Every time this line prints, the component function ran. It is a quick way to check re-renders without the Profiler; delete it afterwards.
- State that triggers re-renders
const [count, setCount] = useState(0);Each setCount re-renders App, and without memo every child would re-render with it.
- Recreated, but harmless here
const lessons = ['JSX', 'Props', 'State'];The array is new on every render, but each child only receives a string, so memo's comparison still works. Passing the array itself as a prop would break it.
- Primitive prop, stable key
<LessonItem key={lesson} title={lesson} />The key keeps each item's identity across renders, and title is a string, so equal values count as unchanged.
On the first render the console shows "render lesson: JSX", "render lesson: Props" and "render lesson: State", and the page shows "Clicked 0" with three list items. Each click changes the button to "Clicked 1", "Clicked 2" and so on, but no new "render lesson" lines appear. Under Strict Mode in development the first render runs twice, so those lines may show up twice.Fixing the ProductList from the problem
Moving the style to a constant outside the component means it is no longer a new object on every render. The handler becomes one useCallback function that takes an id, and each row calls it with its own product.id. The filter goes into useMemo, so it reruns only when query or products change.
const ROW_STYLE = { padding: 8 };
const ProductRow = memo(function ProductRow({ product, onSelect }) {
return <li style={ROW_STYLE} onClick={() => onSelect(product.id)}>{product.name}</li>;
});
function ProductList({ products, onPick }) {
const [query, setQuery] = useState('');
const visible = useMemo(
() => products.filter((p) => p.name.includes(query)),
[products, query],
);
const handleSelect = useCallback((id) => onPick(id), [onPick]);
return visible.map((p) => (
<ProductRow key={p.id} product={p} onSelect={handleSelect} />
));
}Reading a Profiler recording
1. Record one interaction only
Press record, type one character or click one button, then stop. A short recording makes each commit easy to compare.
2. Pick the slowest commit
The bar chart at the top shows how long each commit took. Select the tallest bar and look for the widest, most intensely coloured component in the flamegraph.
3. Turn on "why did this render"
With "Record why each component rendered" enabled in the Profiler settings, each component lists the prop or state change that caused its render. Props like style and onSelect from the problem section show up right there.
In real projects
In real projects
In production apps most performance problems come not from missing memo but from too much data, oversized bundles or network waterfalls. Tables with thousands of rows use a virtualization library such as TanStack Virtual to render only the visible rows. Routes are split with lazy() so code the first page does not need is downloaded later.
To separate typing in a search box from a heavy list update, useDeferredValue lets the list update a little later while the input stays fast. Teams watch user-facing numbers such as Lighthouse scores or Web Vitals like INP, and fix the pages that are actually slow first. A cheap phone on a slow network is a better test device than a fast developer laptop.
Common mistakes
Common mistakes
Wrapping every component in memo
On a component whose props change on every render, memo only adds comparison work and never gets to skip anything, while the code gets harder to read. Add it only where the Profiler shows a slow component.
Wrong useMemo dependencies
Writing useMemo(() => filter(items, query), [items]) without query keeps showing stale results while the user types. List every prop and state value the callback uses, and listen to eslint-plugin-react-hooks warnings.
Measuring in a development build
In development React runs many extra checks and Strict Mode renders twice, so the numbers are inflated. A development profile is fine for comparing components, but check how fast things really are with a production build.
Mini challenge
A fast contact list
Write a ContactList with a search box, a theme toggle button and a favourite checkbox per row. Toggling the theme must not recompute the filter or re-render the rows. Toggling one favourite must re-render only that row.
- Wrap ContactRow in memo
- Make the filtered result a useMemo that depends on [contacts, query]
- Write toggleFavorite with useCallback and an empty dependency array by using an updater function in setContacts
- Give the input an aria-label and show how many contacts match
import { memo, useCallback, useMemo, useState } from 'react';
const ContactRow = memo(function ContactRow({ contact, onToggle }) {
// TODO: <li> with a labelled checkbox (checked = contact.favorite)
// that calls onToggle(contact.id), then the contact's name
});
export default function ContactList({ initialContacts }) {
// TODO: state for contacts, query and theme ('light' | 'dark')
// TODO: visible = useMemo(filter by name, case-insensitive)
// TODO: toggleFavorite = useCallback(id => setContacts(list => ...), [])
// TODO: theme button, search input, "<n> contacts", list of ContactRow
}Expected: In the Profiler, clicking the theme button renders only ContactList and every ContactRow shows "Did not render". Clicking one favourite renders exactly one ContactRow. Typing "an" shows only the matching contacts and their count.
Show hint
With an updater such as setContacts((list) => list.map(...)), the callback never reads contacts directly, so useCallback can have no dependencies. Returning unchanged contact objects as they are inside map lets memo skip those rows.
Show solution
import { memo, useCallback, useMemo, useState } from 'react';
const ContactRow = memo(function ContactRow({ contact, onToggle }) {
return (
<li>
<label>
<input
type="checkbox"
checked={contact.favorite}
onChange={() => onToggle(contact.id)}
/>
{contact.name}
</label>
</li>
);
});
export default function ContactList({ initialContacts }) {
const [contacts, setContacts] = useState(initialContacts);
const [query, setQuery] = useState('');
const [theme, setTheme] = useState('light');
const visible = useMemo(() => {
const q = query.trim().toLowerCase();
return contacts.filter((c) => c.name.toLowerCase().includes(q));
}, [contacts, query]);
const toggleFavorite = useCallback((id) => {
setContacts((list) =>
list.map((c) => (c.id === id ? { ...c, favorite: !c.favorite } : c)),
);
}, []);
return (
<div className={theme}>
<button onClick={() => setTheme((t) => (t === 'light' ? 'dark' : 'light'))}>
Theme: {theme}
</button>
<input
aria-label="Search contacts"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<p>{visible.length} contacts</p>
<ul>
{visible.map((c) => (
<ContactRow key={c.id} contact={c} onToggle={toggleFavorite} />
))}
</ul>
</div>
);
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Three re-render causes: own state, parent re-render, changed context
- Measure with the Profiler before a change and again after it
- Consider structural fixes such as moving state down or virtualization before memo
- memo compares with Object.is, so keep object and function props stable with useMemo and useCallback
- React Compiler can automate memoization, but it does not replace measuring
React Compiler v1.0 — React