ReactMedium
What is useCallback?
useCallback(fn, deps) returns the same function reference across renders until a dependency changes. It does not make functions faster; it keeps their identity stable so memoized children (React.memo) do not re-render and effects that depend on the function do not re-run. The React Compiler now handles this automatically in most code.
Equivalent to
useCallback(fn, deps) is the same as useMemo(() => fn, deps).
When it matters
- Passing a callback to a child wrapped in
React.memo. - A function used as a dependency of
useEffector another hook in a child or custom hook. - Returning functions from a custom hook so consumers can depend on them.
- Passing callbacks to context values (memoize the whole value).
When it does not
- Callbacks passed to plain DOM elements (
<button onClick>): DOM elements do not care about identity. - Children that are not memoized: they re-render anyway.
Avoiding stale closures
If the callback reads state, list it in deps, or use the updater form (setCount((c) => c + 1)) so the callback needs fewer dependencies.
Modern alternatives
- React Compiler: memoizes callbacks automatically; keep
useCallbackonly where you need precise control. useEffectEvent(React 19.2): for functions called from effects that should read the latest props without re-running the effect. It replaces manyuseCallback+ ref workarounds.
Code example
tsx
1import { memo, useCallback, useState } from "react";23const TodoItem = memo(function TodoItem({4 todo,5 onToggle,6}: {7 todo: { id: number; text: string; done: boolean };8 onToggle: (id: number) => void;9}) {10 console.log("render", todo.id);11 return (12 <li>13 <input type="checkbox" checked={todo.done} onChange={() => onToggle(todo.id)} /> {todo.text}14 </li>15 );16});1718export function TodoList() {19 const [todos, setTodos] = useState([20 { id: 1, text: "Learn hooks", done: false },21 { id: 2, text: "Ship", done: false },22 ]);23 const [filter, setFilter] = useState("");2425 // Stable identity: typing in the filter does not re-render every TodoItem26 const toggle = useCallback((id: number) => {27 setTodos((ts) => ts.map((t) => (t.id === id ? { ...t, done: !t.done } : t))); // updater: no deps needed28 }, []);2930 return (31 <>32 <input value={filter} onChange={(e) => setFilter(e.target.value)} />33 <ul>{todos.filter((t) => t.text.includes(filter)).map((t) => <TodoItem key={t.id} todo={t} onToggle={toggle} />)}</ul>34 </>35 );36}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.