Sub topic 8
Returning stable functions with useCallback
This chapter assumes you know useState and useEffect, can read closures and arrow functions, and have read the earlier chapters on hook API design and dependency arrays. Here you will learn when a hook should return a function with a stable identity, how useCallback provides that, and where it does not help.
Why function identity matters
A function component runs again on every render. Any function declared inside it is created anew each time. Two functions with the same code are still different values when compared with ===.
function makeHandler() {
return () => console.log('hi');
}
const a = makeHandler();
const b = makeHandler();
console.log(a === b); // falseMost of the time this does not matter. It matters when something compares the function to its previous value:
- A dependency array in
useEffect,useMemo, oruseCallback. A new function each render means the effect re-runs each render. - A child wrapped in
React.memo. A new function prop makes the memo check fail, so the child re-renders anyway. - Code outside React that stores the function, such as an event listener you add and remove.
A hook is code that many components will call, and you do not control how they use what it returns. If your hook returns a function, you decide whether its identity is stable. A stable identity is a promise to callers: they can put it in a dependency array without causing extra work.
What useCallback does
useCallback(fn, deps) returns the same function object across renders as long as every value in deps is unchanged. When a dependency changes, it returns the new fn you passed in that render.
Here is the toggle hook from the Topic Spine:
import { useState, useCallback } from 'react';
export function useToggle(initial = false) {
const [on, setOn] = useState(initial);
const toggle = useCallback(() => setOn((value) => !value), []);
return [on, toggle];
}toggle has an empty dependency array, so it is created once and reused. That is safe because it uses only setOn, which React guarantees is stable, and it uses the functional form setOn((value) => !value). The function never reads on from the render's closure, so it can never go stale.
A caller can now write this without worry:
useEffect(() => {
window.addEventListener('keydown', toggle);
return () => window.removeEventListener('keydown', toggle);
}, [toggle]);The effect subscribes once, because toggle never changes.
The functional update trick
The most common way to get a stable function is to avoid reading state in it. Compare these two versions of a counter hook.
import { useState, useCallback } from 'react';
// Unstable: new function whenever count changes
export function useCounterUnstable() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount(count + 1), [count]);
return { count, increment };
}
// Stable: identity never changes
export function useCounter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => setCount((c) => c + 1), []);
return { count, increment };
}The first version lists count as a dependency because the function reads it. Each click changes count, so increment changes on each click. The second version asks React for the current value inside the updater, so it needs no dependencies.
What goes in the dependency array
useCallback follows the same rule as every other hook with dependencies. Every reactive value the function reads from the component or hook scope must be listed. Reactive values are props, state, and anything computed from them during render.
import { useState, useCallback } from 'react';
export function useStep(step) {
const [value, setValue] = useState(0);
const advance = useCallback(() => {
setValue((v) => v + step);
}, [step]);
return [value, advance];
}advance reads step, a parameter of the hook, so step must be in the array. While step stays the same, advance keeps its identity. When the caller passes a new step, advance changes, and that is correct: the old function would add the wrong amount.
Leaving step out would produce a stale closure. The function would keep adding the first step value forever. The react-hooks/exhaustive-deps lint rule catches this, so keep it enabled.
Hooks that accept callbacks
A harder case arises when your hook takes a function from the caller and returns a wrapper around it.
import { useState, useCallback } from 'react';
export function useAsyncAction(action) {
const [pending, setPending] = useState(false);
const run = useCallback(
async (...args) => {
setPending(true);
try {
return await action(...args);
} finally {
setPending(false);
}
},
[action]
);
return { pending, run };
}run depends on action. If the caller passes an inline arrow function, action is new on every render, and run is new on every render too. Your useCallback is then doing nothing useful. The stability you promise depends on the caller's behavior.
You have three options:
| Option | How it works | Trade-off |
|---|---|---|
| Document that `action` must be memoized | The caller wraps it in `useCallback` | Easy for you, easy for callers to forget |
| Do not promise stability | Skip `useCallback` and say so | Honest, but callers cannot use `run` in dependency arrays |
| Read `action` through a ref | A ref holds the latest `action`, and `run` has no dependencies | Stable for any caller, but adds a ref and an effect |
The ref approach is covered in the chapter on reading the latest callback through a ref. In short, it looks like this:
import { useState, useCallback, useRef, useEffect } from 'react';
export function useAsyncAction(action) {
const [pending, setPending] = useState(false);
const actionRef = useRef(action);
useEffect(() => {
actionRef.current = action;
});
const run = useCallback(async (...args) => {
setPending(true);
try {
return await actionRef.current(...args);
} finally {
setPending(false);
}
}, []);
return { pending, run };
}Now run is stable no matter what the caller passes, and it always calls the latest action.
How it works internally
On the first render, React stores the function and the dependency array in the hook's slot for that component. On later renders, it compares the new dependencies to the stored ones using Object.is, one item at a time. If all match, it returns the stored function and discards the new one. If any differ, it stores and returns the new function.
Two consequences follow:
- The function you pass is still created on every render.
useCallbackdoes not avoid that cost. It only decides which function object you keep. - Dependencies compare by identity, not by content. An object or array literal in the dependency array, or one created during render, changes every render.
import { useCallback } from 'react';
export function useSearch(query) {
const options = { query, limit: 10 }; // new object every render
// Never stable: `options` differs every render
const search = useCallback(() => fetchResults(options), [options]);
return search;
}Depend on the primitives instead: [query] with limit as a constant, and build the object inside the callback.
When useCallback is not worth it
useCallback has a cost: more code, a dependency array to maintain, and a comparison on each render. It pays off only when identity is observed. Skip it when:
- The function is used only in a plain event handler like
onClickon a DOM element, and nothing compares it. - The function is used only inside the render itself.
- The function is passed to a child that is not memoized. That child re-renders with its parent anyway.
For a hook that is published for reuse, the balance shifts. You cannot see how callers use the return value, so stable identity for returned functions is a safe default, as long as you can achieve it without hiding bugs.
Seeing the effect
This sequence shows how a stable function prevents effect re-runs in the caller.
Testing stability
You can check the promise directly with renderHook. Keep the first returned function and compare it after a re-render.
import { renderHook, act } from '@testing-library/react';
import { useToggle } from './useToggle';
test('toggle keeps the same identity across renders', () => {
const { result, rerender } = renderHook(() => useToggle());
const first = result.current[1];
act(() => {
result.current[1]();
});
rerender();
expect(result.current[0]).toBe(true);
expect(result.current[1]).toBe(first);
});Common mistakes
- Omitting a dependency to keep the function stable. This creates a stale closure.
- Wrapping a function in
useCallbackbut passing an inline callback from the caller into its dependencies, so it changes every render anyway. - Putting an object or array created in render into the dependency array.
- Using
useCallbackeverywhere by habit, which adds noise without any benefit. - Returning some functions stable and others not, with no documentation. Callers will not know which ones are safe in dependency arrays.
Exercise
A hook has const [count, setCount] = useState(0); const reset = useCallback(() => setCount(0), []); and const add = useCallback((n) => setCount(count + n), []);. One of these is buggy. Which one, why, and how do you fix it while keeping the function stable?
Show answer
add is buggy. It reads count from the render in which it was created, but its dependency array is empty, so it keeps the first render's count (0) forever and every call sets the count to n. reset is fine because it reads no reactive value. Fix add with the functional update setCount((c) => c + n), which needs no dependency on count, so the empty array stays correct.
Exercise
Your hook useInterval(callback, delay) returns stop. Callers pass inline arrow functions as callback. Why would useCallback(() => callback(), [callback]) fail to make a stable function, and what is one way to fix it?
Show answer
Inline arrow functions are new on every render, so callback changes every render and the dependency array makes the returned function change too. Store the latest callback in a ref, update the ref in an effect, and call callbackRef.current() inside a function wrapped in useCallback with an empty dependency array.