Sub topic 8
Returning stable functions with useCallback
This chapter assumes you know useState and useEffect, closures, and the Rules of Hooks. It also assumes you have written a small custom hook such as useToggle.
Why function identity matters
Every render creates new function objects. A function defined in a hook body is a different object on each render, even if its code is identical. Most of the time this is harmless. It matters in two cases:
- The function is passed to a child wrapped in
React.memo. A new identity makes the child re-render. - The function is listed in the dependency array of an effect or another hook. A new identity makes the effect re-run.
If your hook returns functions, its callers may do either of these things. A stable function reference spares them the problem.
Caching a function with useCallback
useCallback(fn, deps) returns the same function object on every render until a value in deps changes.
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}The dependency array is empty, and that is correct. setOn never changes identity, and the updater function receives the current value as its argument. The callback never reads on from the surrounding render, so it has nothing to go stale.
The stale closure trap
Writing setOn(!on) with an empty array looks similar but is a bug:
// Bug: `on` is captured from the first render and never updates.
const toggle = useCallback(() => setOn(!on), []);The callback always sees the on from the render where it was created. The toggle would work once and then stop. You have two fixes:
- Add
onto the dependency array. The function is then correct, but it gets a new identity every timeonchanges. - Use the functional updater, as in
useToggle. The function stays stable and correct.
Prefer the second fix when the new state depends only on the old state.
When a callback does need an outside value, list it as a dependency:
import { useState, useCallback } from 'react';
export function useCounter(step = 1) {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount((c) => c + step), [step]);
const reset = useCallback(() => setCount(0), []);
return { count, increment, reset };
}reset never changes. increment changes only when step changes. That is what stable means here: the identity changes only when the behavior does.
When to use it
| Situation | Use useCallback? |
|---|---|
| The hook returns a function that callers may pass to a memoized child or put in a dependency array | Yes |
| The function is only used inside the hook's own effect | No. Define it inside the effect. |
| The function is only passed to a plain DOM element such as `<button>` | Usually no |
If a callback must always see the latest value and you cannot list that value as a dependency without churn, a ref is the usual answer. A later chapter covers that pattern.
Exercise
A hook contains const add = useCallback((n) => setTotal(total + n), []);. Why is this wrong, and what are two ways to fix it?
Show answer
The empty array means add captures total from the first render, so it always computes from the initial value. Fix 1: add total to the dependency array, which makes add get a new identity whenever total changes. Fix 2: use a functional updater, setTotal((t) => t + n), which keeps the array empty and the function stable.