Sub topic 8
Stable functions with useCallback
This chapter assumes you know function components, useState, props, and that JavaScript functions are reference values. It builds on React.memo, referential equality, and useMemo.
Why function props break memo
Every render of a component runs its body again. Any function defined in the body is created fresh each time. Two functions with identical code are still different objects, and Object.is treats them as different.
So when a parent passes an inline function to a child wrapped in memo, the child sees a new prop on every parent render. The shallow comparison fails and the child re-renders anyway.
useCallback fixes this. It returns the same function reference between renders until a value in its dependency array changes.
const handleSelect = useCallback((id) => {
setSelectedId(id);
}, []);useCallback(fn, deps) behaves like useMemo(() => fn, deps). It caches the function itself and does not call it.
A worked example
In this list, Row is wrapped in memo. handleSelect keeps the same reference across renders, so selecting a row does not re-render rows whose item is unchanged.
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>
</>
);
}The first render logs every row. After you click a row, List re-renders because its state changed, but Row is skipped. item is the same object and onSelect is the same function.
Writing the dependency array
The dependency array lists every reactive value the function reads: props, state, and variables from the component body. React compares each entry with Object.is after each render. If any entry changed, it creates a new function.
An empty array is safe in the example above because setSelectedId is a state setter, which React keeps stable. A function that reads state needs that state in the array:
const handleAdd = useCallback(() => {
setCount(count + 1);
}, [count]);This works, but handleAdd changes on every click, which weakens the benefit. When you only need the previous value, use an updater function and drop the dependency:
const handleAdd = useCallback(() => {
setCount((c) => c + 1);
}, []);Common errors
- Omitting a dependency. The function keeps the values from the render where it was created, so it reads stale state. The
react-hooks/exhaustive-depslint rule catches this. - Using
useCallbackwithoutmemo. If the child is not memoized, it re-renders whenever the parent does, so the stable reference changes nothing. - Passing another unstable prop. One new object or array prop is enough to defeat
memo, even if the function is stable. - Wrapping every handler. Each
useCallbackcosts memory and a dependency comparison. Use it where a stable reference matters.
When it is worth it
Use useCallback when the function is passed to a memo child, or when it is a dependency of useEffect or useMemo and you do not want those to re-run on each render. Check the Profiler first, as covered earlier. Otherwise skip it.
Exercise
A parent renders <Child onSave={() => save(id)} />, where Child is wrapped in memo. The Profiler shows Child re-rendering on every parent render. Why, and how do you fix it?
Show answer
The inline arrow function is a new object on each parent render, so memo's shallow comparison sees a changed onSave prop. Wrap it in useCallback(() => save(id), [id]) (and add save to the array if it is not a stable import) so the reference only changes when id changes.
Exercise
You wrote const inc = useCallback(() => setCount(count + 1), []);. The button increases the count from 0 to 1 and then stays at 1. What is wrong, and what are two ways to fix it?
Show answer
The empty array means inc keeps the count value from the first render, which is 0, so every call sets the count to 1. Either add count to the dependency array, or use the updater form setCount((c) => c + 1) and keep the empty array.