Sub topic 9
Memoizing with React.memo, useMemo, and useCallback
Memoization means caching a result and reusing it when the inputs have not changed. React offers three tools for this. React.memo skips re-rendering a component, useMemo caches a computed value, and useCallback caches a function. This chapter covers how each one works and why a memoized component can still re-render. It also covers how to confirm in the Profiler that a change helped.
Prerequisites
This chapter assumes you can:
- Write function components with props, state, and hooks.
- Explain the difference between a render and a commit.
- Record a session in the React DevTools Profiler and use its "Why did this render?" information.
It also assumes you have already found a component that re-renders without needing to, and tried moving state down first.
Where memoization fits
When a parent re-renders, React re-renders all of its children by default, even if their props are identical. Re-rendering means calling the component function again. React then compares the output with the previous output and commits only the real DOM differences. Skipped commits are cheap, but the render calls can be expensive for large subtrees.
Memoization targets that render work. Reach for it after you have measured a slow render and after moving state down was not enough.
React.memo: skip renders when props are equal
memo wraps a component. Before re-rendering it, React compares each new prop with the previous one using Object.is. If every prop matches, React reuses the last result and does not call the component.
import { memo } from "react";
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});The comparison is shallow. Two props count as equal only if they are the same value for primitives, or the same reference for objects, arrays, and functions. This is the main source of confusion. Objects, arrays, and functions created inside a component body get a new identity on every render.
import { memo } from "react";
const Chart = memo(function Chart({ options }) {
return <pre>{JSON.stringify(options)}</pre>;
});
export function Panel({ title }) {
// A new object is created on every render, so memo(Chart) never skips.
return (
<section>
<h2>{title}</h2>
<Chart options={{ color: "red" }} />
</section>
);
}Here memo does nothing, and it adds a comparison cost on every render. There are two fixes. If the value never changes, move it outside the component:
const CHART_OPTIONS = { color: "red" };
// <Chart options={CHART_OPTIONS} />If it depends on props or state, cache it with useMemo or useCallback.
useCallback: keep a function's identity
useCallback(fn, deps) returns the same function object between renders until a dependency changes. Its main use is feeding a stable function to a memoized child.
import { memo, useCallback, useState } from "react";
const Row = memo(function Row({ item, onSelect }) {
return <li onClick={() => onSelect(item.id)}>{item.name}</li>;
});
export function List({ items }) {
const [selectedId, setSelectedId] = useState(null);
// Stable identity lets memo(Row) skip re-rendering when only selectedId changes.
const handleSelect = useCallback((id) => setSelectedId(id), []);
return (
<>
<p>Selected: {selectedId}</p>
<ul>
{items.map((item) => (
<Row key={item.id} item={item} onSelect={handleSelect} />
))}
</ul>
</>
);
}Clicking a row changes selectedId, so List re-renders. Every Row receives the same item and the same handleSelect, so each Row is skipped.
useCallback alone does nothing useful. It pays off only when the receiving component is wrapped in memo, or when the function is a dependency of another hook such as useEffect.
Keep the dependency array small. If the callback needs the current state, use the functional form of the setter instead of listing the state:
const increment = useCallback(() => setCount((c) => c + 1), []);Listing count as a dependency would create a new function on every change and defeat the purpose. Leaving a needed value out of the array is worse. The callback then keeps a stale copy of that value from an earlier render.
useMemo: cache a value
useMemo(calculate, deps) runs calculate during render and stores the result. It recalculates only when a dependency changes.
import { useMemo, useState } from "react";
export function FilteredList({ items }) {
const [filter, setFilter] = useState("");
const [dark, setDark] = useState(false);
// Recomputed only when items or filter change, not when dark toggles.
const visible = useMemo(
() => items.filter((item) => item.name.toLowerCase().includes(filter.toLowerCase())),
[items, filter]
);
return (
<div className={dark ? "dark" : "light"}>
<button onClick={() => setDark((d) => !d)}>Toggle theme</button>
<input value={filter} onChange={(e) => setFilter(e.target.value)} />
<ul>
{visible.map((item) => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}useMemo has two legitimate uses:
- Skipping a calculation that is measurably slow, such as filtering or sorting thousands of items.
- Keeping an object or array stable so a memoized child, or a hook dependency, does not see a new reference.
It does not help with cheap work. Filtering ten items is faster than the bookkeeping useMemo adds. As a rough guide, only memoize a calculation if it takes about a millisecond or more, and measure on a production build. If items itself is a new array on every render, useMemo here recalculates every time. The cache is only as stable as its dependencies.
React treats useMemo as a performance hint. It may discard cached values in some situations, so your code must stay correct if the calculation runs again.
Comparing the three tools
| Tool | What it caches | Skips | Works only if |
|---|---|---|---|
| `React.memo` | A component's rendered output | Calling the component function | All props are referentially stable between renders |
| `useCallback` | A function reference | Nothing by itself | The function goes to a memoized child or a hook dependency |
| `useMemo` | Any computed value | A calculation, or a new reference | Dependencies are stable and the value is read again |
Why a memoized component still re-renders
A memo component can re-render for reasons that no props comparison can prevent:
- Its own state changes.
memoonly guards against parent re-renders. - It reads a context whose value changed. Context updates bypass
memo. Splitting one large context into smaller ones limits the damage. - A prop is a new reference. Inline objects, arrays, and arrow functions are the usual culprits. A
childrenprop is also a new element object on each parent render, unless the parent itself did not re-render. - A dependency is unstable. A
useCallbackoruseMemowhose own inputs change every render hands out a new value every render.
Confirming that memoization worked
Memoization is a hypothesis, so check it with the Profiler. Record the same interaction before and after the change, then compare these signals:
- In the flamegraph, a memoized component that was skipped appears gray. A component that rendered appears colored.
- With "Record why each component rendered" enabled, a failing
memoshows "Props changed" followed by the prop name, such asonSelect. That name is the reference to stabilize. - Compare the commit duration. If it did not drop by a meaningful amount, remove the memoization to keep the code simple.
Memoization adds code to maintain, and every wrapped component pays for prop comparisons. Apply it where the Profiler shows repeated expensive renders. Also check whether your project uses the React Compiler. It can add memoization automatically at build time, which makes manual useMemo and useCallback mostly unnecessary in compiled code.
Exercise
A parent holds a text input in state and renders <Chart options={{ color: "red" }} />, where Chart is wrapped in memo. The Profiler shows Chart re-rendering on every keystroke with "Props changed: options". Give two ways to fix this, and say which you would pick if the options never change.
Show answer
Move the object outside the component as a constant, or wrap it in useMemo(() => ({ color: "red" }), []). If the options never change, use the module-level constant. It needs no hook, no dependency array, and no per-render work. Moving the text input into its own component would also work, because the parent would no longer re-render on each keystroke.
Exercise
You wrap handleSelect in useCallback, but Row is not wrapped in memo. Do the rows skip rendering when the parent re-renders? Why or why not?
Show answer
No. Without memo, React re-renders every child whenever the parent renders, regardless of whether the props changed. useCallback only makes the function reference stable. It takes effect when the child compares props, which happens only with memo, or when the function is a hook dependency.