Sub topic 8
Stable functions with useCallback
This chapter assumes you know function components, useState and useEffect, passing props, and that JavaScript functions and objects are compared by reference. It also assumes you have read the earlier chapters on React.memo, unstable props, useMemo, and dependency arrays.
The problem useCallback solves
A function declared inside a component is created again on every render. Two renders produce two different function objects, even when the code is identical. Under Object.is, the comparison React uses for props, those functions are not equal.
That matters when the function is passed to a component wrapped in React.memo. The memo check sees a changed prop and re-renders the child, so the memoization does nothing.
useCallback returns the same function object across renders until its dependencies change. It is the function-shaped version of useMemo.
const handleSelect = useCallback((id) => {
setSelectedId(id);
}, []);React calls useCallback(fn, deps) on every render. On the first render it stores fn and returns it. On later renders it compares deps with the stored array. If every entry is equal, it returns the stored function and ignores the new fn. If any entry differs, it stores the new fn and returns that.
Relationship to useMemo
useCallback(fn, deps) behaves the same as useMemo(() => fn, deps). The only difference is what is cached. useMemo calls your function and caches the result. useCallback caches the function itself and never calls it.
import { useCallback, useMemo } from 'react';
function Example({ onSave }) {
// These two are equivalent.
const a = useCallback(() => onSave('draft'), [onSave]);
const b = useMemo(() => () => onSave('draft'), [onSave]);
return null;
}Use useCallback because it is shorter and signals your intent. There is no performance difference.
A complete example
The List component below keeps selectedId in state. Every selection re-renders List. Without useCallback, every Row would also re-render, because each render of List would create a new onSelect.
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 must both be true for this to work:
Rowis wrapped inmemo, so React compares its props.handleSelectis stable, and eachitemkeeps the same reference between renders.
If you remove either one, every row logs render row on each click. The onClick={() => onSelect(item.id)} inside Row is fine. It is a new function on every Row render, but it is passed to a DOM element, not to a memoized component.
Dependencies and stale closures
A function closes over the variables that were in scope when it was created. A cached function keeps those old values. If the function reads a prop or state value that is missing from the dependency array, it keeps using the value from the render where it was cached. This is a stale closure.
import { useCallback, useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
// Broken: count is read but not listed, so it is always 0 here.
const logBroken = useCallback(() => {
console.log('count is', count);
}, []);
// Correct: a new function is created whenever count changes.
const logCorrect = useCallback(() => {
console.log('count is', count);
}, [count]);
return (
<>
<button onClick={() => setCount(count + 1)}>Add</button>
<button onClick={logBroken}>Log (stale)</button>
<button onClick={logCorrect}>Log (current)</button>
</>
);
}Click Add three times, then click each log button. The first prints count is 0. The second prints count is 3.
Include every reactive value the function reads: props, state, and variables or functions declared in the component body. The react-hooks/exhaustive-deps ESLint rule reports missing entries. Do not silence it. Fix the function so the dependency list is honest.
Keeping the function stable with updater functions
Listing a dependency makes the function change when that value changes, which can defeat the memoization you wanted. For state, you can often remove the dependency by using the updater form of the setter.
import { memo, useCallback, useState } from 'react';
const AddButton = memo(function AddButton({ onAdd }) {
console.log('render AddButton');
return <button onClick={onAdd}>Add</button>;
});
export function Tally() {
const [count, setCount] = useState(0);
// Reads the latest count through the updater, so no dependency is needed.
const handleAdd = useCallback(() => {
setCount((c) => c + 1);
}, []);
return (
<>
<p>Count: {count}</p>
<AddButton onAdd={handleAdd} />
</>
);
}setCount((c) => c + 1) receives the current value from React, so the function never reads count from its closure. The dependency array can stay empty, and AddButton renders only once. Setter functions from useState have a stable identity, so they do not need to be listed either.
When a callback needs to read a value that changes often and cannot use an updater, you have three options:
- Accept that the function changes and let the child re-render.
- Pass the value to the child as a prop, and let the child call back with it.
- Move the logic so that the callback does not need the value.
Callbacks with arguments in lists
In a list, each row often needs a handler for its own item. Creating () => onSelect(item.id) in the parent produces a different function per row on every render. The common fix is to pass one stable handler that accepts an argument, and let the child supply it.
import { memo, useCallback, useState } from 'react';
const Item = memo(function Item({ id, label, onToggle }) {
console.log('render item', id);
return <li onClick={() => onToggle(id)}>{label}</li>;
});
export function Checklist({ items }) {
const [done, setDone] = useState(() => new Set());
const handleToggle = useCallback((id) => {
setDone((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}, []);
return (
<ul>
{items.map((item) => (
<Item
key={item.id}
id={item.id}
label={done.has(item.id) ? `${item.label} (done)` : item.label}
onToggle={handleToggle}
/>
))}
</ul>
);
}Here the primitive props id and label compare by value. Toggling one item changes only that item's label, so only that Item re-renders.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| `useCallback` on a function passed to a non-memoized child | No benefit. The child re-renders anyway. | Wrap the child in `memo`, or remove `useCallback`. |
| Omitting a dependency | Stale closure bug. | Add the dependency, or use an updater function. |
| Passing an unstable value as a dependency, such as an inline object | The callback changes on every render. | Stabilize the value with `useMemo`, or depend on its primitive fields. |
| Wrapping `useCallback` around a function you call in render | Pointless. Nothing compares the reference. | Call a plain function. |
| Using `useCallback` while another prop is still unstable | `memo` still sees a changed prop. | Stabilize every prop of the memoized child. |
The last row is the most common cause of "I added useCallback and nothing changed". One unstable prop is enough to re-render the child. Check all of them.
import { memo, useCallback } from 'react';
const Panel = memo(function Panel({ style, onClose }) {
return <div style={style} onClick={onClose}>Panel</div>;
});
export function Screen() {
const handleClose = useCallback(() => console.log('closed'), []);
// Broken: the style object is new each render, so Panel still re-renders.
return <Panel style={{ color: 'red' }} onClose={handleClose} />;
}Move the style object outside the component, since it never changes, or wrap it in useMemo if it depends on props or state.
Debugging whether it works
Do not assume a useCallback helps. Check it.
- Open the React DevTools Profiler and record the interaction.
- Select the child component in the flame graph.
- Read the "Why did this render?" note. It names the props that changed, such as
onSelect changed. - If the note names a function you already wrapped, check its dependency array for a value that changes on each render.
You can also log inside the component, as the examples here do with console.log. In development, React Strict Mode renders components twice on purpose, so expect doubled logs.
When to use useCallback
Use it in these cases:
- The function is passed as a prop to a component wrapped in
memo. - The function is a dependency of
useEffect,useMemo, or anotheruseCallback, and you do not want the effect to run on every render. - The function is returned from a custom hook, where you cannot know how callers will use it.
Skip it for a function used only in an event handler on a DOM element, for a child that is not memoized, and for code that has not been measured to be slow. Each useCallback adds a dependency comparison and keeps the old closure alive in memory. The cost is small, but the benefit is zero when nothing downstream compares the reference.
import { useCallback, useEffect, useState } from 'react';
export function Feed({ userId }) {
const [posts, setPosts] = useState([]);
const load = useCallback(async () => {
const res = await fetch(`/api/users/${userId}/posts`);
setPosts(await res.json());
}, [userId]);
// The effect re-runs only when userId changes, because load does too.
useEffect(() => {
load();
}, [load]);
return <p>{posts.length} posts</p>;
}In this case useCallback serves correctness as much as speed. Without it, load would be new on every render and the effect would fetch on every render. For a function used only inside one effect, it is usually simpler to define it inside the effect and skip useCallback.
Exercises
Exercise
A parent renders <Child onSave={() => save(id)} />, and Child is wrapped in memo. You change the parent to const onSave = useCallback(() => save(id), [id]);. id is a prop that stays the same during typing in an input in the parent. Will typing re-render Child? What changes if id changes on every parent render?
Show answer
Typing will not re-render Child, as long as its other props are also stable. id is unchanged, so useCallback returns the same function and memo sees equal props. If id changes on every parent render, the dependency check fails every time, a new function is created, and Child re-renders on every parent render. The fix is to stabilize id, not to change useCallback.
Exercise
This callback logs the wrong value. Explain why and give two fixes. const [text, setText] = useState(''); const send = useCallback(() => { api.post(text); }, []);
Show answer
The empty dependency array caches the function from the first render, where text is ''. The closure never sees later values. Fix one: add text to the array, [text], so a new function is created whenever text changes. Fix two: store the latest value in a ref and read ref.current inside the callback, or pass text as an argument from the component that owns it. Adding the dependency is the simplest and the one the lint rule suggests.
Exercise
You add useCallback to every function in a component whose children are not wrapped in memo. What does it improve?
Show answer
Nothing visible. Children that are not memoized re-render whenever the parent does, whatever their props are, so a stable function reference is never used. The hooks add small comparison and memory costs. Remove them, or wrap the children in memo if the profiler shows those re-renders are costly.