TExcelTAD
Home › React › React useCallback

React useCallback

Every time a component renders, functions defined inside it are created anew. Usually that's perfectly fine. But sometimes a function's identity matters: when it is passed to a child wrapped in memo, or when it is a dependency of an effect. useCallback returns the same function object between renders until one of its dependencies changes.

jsx
const handleSave = useCallback(() => {
  save(draft);
}, [draft]);   // a new function only when draft changes

Functions are new on every render

JavaScript compares functions by reference. Two functions with the same code are still different objects:

jsx · try it yourself
import { useState, useCallback, useRef } from 'react';

export default function App() {
  const [count, setCount] = useState(0);
  const plain = () => console.log('plain');
  const stable = useCallback(() => console.log('stable'), []);

  const prev = useRef({ plain: null, stable: null });
  const plainChanged = prev.current.plain !== null && prev.current.plain !== plain;
  const stableChanged = prev.current.stable !== null && prev.current.stable !== stable;
  prev.current = { plain, stable };

  return (
    <div>
      <button onClick={() => setCount(count + 1)}>Re-render ({count})</button>
      <p>plain function is new this render: <strong>{String(plainChanged)}</strong></p>
      <p>useCallback function is new this render: <strong>{String(stableChanged)}</strong></p>
    </div>
  );
}

After the first click, the plain arrow is a new object each render, while the useCallback version stays identical.

Why identity matters: memo children

memo (covered in the memo lesson) lets a component skip re-rendering when its props haven't changed. But a fresh function prop counts as "changed" every time, which defeats memo. Compare the render counts:

jsx · try it yourself
import { memo, useCallback, useState } from 'react';

const renders = { a: 0, b: 0 };

const ExpensiveButton = memo(function ExpensiveButton({ id, onPress, children }) {
  renders[id] += 1;
  return (
    <button onClick={onPress} style={{ margin: 4 }}>
      {children} (rendered {renders[id]}×)
    </button>
  );
});

export default function App() {
  const [text, setText] = useState('');
  const [clicks, setClicks] = useState(0);

  const unstable = () => setClicks((c) => c + 1);
  const stable = useCallback(() => setClicks((c) => c + 1), []);

  return (
    <div>
      <input value={text} onChange={(e) => setText(e.target.value)} placeholder="Type to re-render App" />
      <p>Clicks: {clicks}</p>
      <ExpensiveButton id="a" onPress={unstable}>Without useCallback</ExpensiveButton>
      <ExpensiveButton id="b" onPress={stable}>With useCallback</ExpensiveButton>
    </div>
  );
}

Type in the input: button A re-renders on every keystroke, button B doesn't. (The counter is stored in a module variable just to display render counts — don't do this in real code.)

Notice setClicks((c) => c + 1): by using the updater form, the callback doesn't need clicks in its dependencies, so it never has to change.

Dependencies

List every value from the component that the function uses — the same rules as useEffect:

jsx · try it yourself
import { useCallback, useEffect, useState } from 'react';

export default function App() {
  const [query, setQuery] = useState('re');
  const [results, setResults] = useState([]);
  const WORDS = ['react', 'redux', 'remix', 'router', 'vite', 'vitest', 'vue'];

  const search = useCallback(() => {
    return WORDS.filter((w) => w.startsWith(query.toLowerCase()));
  }, [query]);  // eslint would also ask for WORDS — move constants outside the component instead

  useEffect(() => {
    console.log(`searching for "${query}"`);
    setResults(search());
  }, [search]);   // runs only when search changes, i.e. when query changes

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <ul>{results.map((r) => <li key={r}>{r}</li>)}</ul>
    </div>
  );
}

Because search is stable between renders with the same query, the effect doesn't re-run needlessly. (In this simple case it would be even cleaner to filter during render — no effect needed.)

useCallback vs. useMemo

useCallback(fn, deps) useMemo(() => value, deps)
Caches the function itself the result of calling a function
Equivalent to useMemo(() => fn, deps) —
Typical use stable event handlers for memo children / effect deps expensive calculations, stable objects

When to use it — and when not

  • ✅ Passing a callback to a component wrapped in memo.
  • ✅ The function is a dependency of useEffect or another hook.
  • ✅ Returning functions from a custom hook, so callers can rely on their identity.
  • ❌ Everywhere "just in case". It adds code and a dependency array to maintain, and gives no benefit when the child isn't memoized.

Note: The React Compiler (an optional build plugin, stable since 2025) memoizes components and callbacks automatically. In projects that use it, you rarely need to write useCallback yourself. It's still essential to understand when reading existing code.

Test yourself

What does useCallback return?

  1. The result of calling the function
  2. The same function object until a dependency changes
  3. A promise
  4. A ref to the function

A memo child re-renders on every parent render even though its props look the same. A likely cause?

  1. It uses useState
  2. The parent passes a new inline function prop each render
  3. memo doesn't work with buttons
  4. The child has a key

useCallback(fn, deps) is equivalent to…

  1. useMemo(fn, deps)
  2. useMemo(() => fn, deps)
  3. useRef(fn)
  4. useEffect(fn, deps)