Category: react
What Does useCallback Do?
Published on 27 Oct 2026
Explanation
useCallback caches a function definition between renders until its dependencies change. It is useful when function identity matters, such as when passing a callback to a memoized child.
Code:
const handleSave = useCallback(() => {
saveDocument(documentId);
}, [documentId]);
Explanation
A memoized child can still rerender if it receives a newly created callback on every parent render. useCallback can keep the callback identity stable when its dependencies have not changed.
Code:
const SaveButton = React.memo(function SaveButton({ onSave }) {
return <button onClick={onSave}>Save</button>;
});
function Editor({ documentId }) {
const handleSave = useCallback(() => saveDocument(documentId), [documentId]);
return <SaveButton onSave={handleSave} />;
}
Explanation
If a callback updates state based on its previous value, a functional state update can remove that state variable from the callback's dependencies.
Code:
const addItem = useCallback((item) => {
setItems((currentItems) => [...currentItems, item]);
}, []);
Explanation
A function declared during rendering changes identity each time. If an effect depends on it, useCallback can stabilize that identity when appropriate; often, moving the function inside the effect is simpler.
Code:
const fetchUser = useCallback(() => {
return fetch(`/api/users/${userId}`).then((res) => res.json());
}, [userId]);
useEffect(() => {
fetchUser().then(setUser);
}, [fetchUser]);
Explanation
Do not wrap every function in useCallback automatically. It adds complexity and is most useful when a stable function identity prevents meaningful work or is required by another Hook's dependency list.
Code:
function Counter() {
const [count, setCount] = useState(0);
// Usually no need to memoize this simple handler.
function increment() {
setCount((value) => value + 1);
}
return <button onClick={increment}>{count}</button>;
}