useMemo and useCallback

Intermediate · 25 min

Memoizing an expensive calculation with useMemo and a stable function reference with useCallback, and the dependency-array discipline both demand.

Before thisWhy React re-renders

tapaScript by Tapas Adhikary · 25 min

useMemo and useCallback

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by tapaScript by Tapas AdhikaryReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • useMemo caches the return value of a calculation across re-renders and only recomputes it when a value in its dependency array changes.
  • useCallback caches a function definition itself, returning the exact same function reference across re-renders as long as its dependencies haven't changed.
  • Both hooks trade memory and a small bookkeeping cost for skipping work; using either on a cheap calculation or an unused function usually makes things slower, not faster, because the dependency comparison itself has a cost.
  • The real payoff shows up in two cases: genuinely expensive computations (sorting or filtering a large list, heavy parsing) and stable references that something else depends on, such as a memoized child's props or a useEffect dependency array.
  • Getting the dependency array wrong is the same failure mode as with useEffect: leave out a value the calculation or function actually uses and you get a stale result that silently doesn't update.
  • Neither hook changes when a component re-renders. They only change whether a specific value or function inside that re-render gets recomputed, which is why they do nothing on their own without React.memo or another consumer to take advantage of them.

Caching a value: useMemo

The previous lesson established that a re-render calls your component function again. Most of what that function does — building JSX, reading a couple of props — is trivial to redo. Some of it isn’t.

function ProductList({ products, query }) {
  const filtered = products
    .filter((p) => p.name.toLowerCase().includes(query.toLowerCase()))
    .sort((a, b) => a.price - b.price);

  return (
    <ul>
      {filtered.map((p) => (
        <li key={p.id}>{p.name} — ${p.price}</li>
      ))}
    </ul>
  );
}

If products has a few thousand entries, filtering and sorting it on every render — including renders caused by something unrelated, like a sidebar toggling open — is wasted work. useMemo lets you cache the result and only redo it when the inputs that matter actually change:

function ProductList({ products, query }) {
  const filtered = useMemo(() => {
    return products
      .filter((p) => p.name.toLowerCase().includes(query.toLowerCase()))
      .sort((a, b) => a.price - b.price);
  }, [products, query]);

  return (
    <ul>
      {filtered.map((p) => (
        <li key={p.id}>{p.name} — ${p.price}</li>
      ))}
    </ul>
  );
}

On every render, React checks the dependency array [products, query] against the values from last time. If both are unchanged (same reference for products, same string for query), React skips calling the function and returns the cached filtered array instead. If either changed, it reruns the calculation and stores the new result.

This is a direct trade: a little memory to hold the cached value and dependencies, plus a comparison on every render, in exchange for skipping the actual work when nothing relevant changed. For a calculation that’s already fast — adding two numbers, formatting one string — that trade is a net loss. The comparison itself isn’t free, and caching something cheaper than the cache check is pointless. useMemo earns its keep on calculations that are measurably expensive, usually because they scale with the size of some collection.

Caching a reference: useCallback

useCallback solves a related but different problem. It doesn’t cache a value — it caches a function reference.

function SearchBox({ onSearch }) {
  const [query, setQuery] = useState("");

  const handleSubmit = useCallback(() => {
    onSearch(query);
  }, [query, onSearch]);

  return <Form onSubmit={handleSubmit} />;
}

Without useCallback, handleSubmit would be a brand-new function object on every render of SearchBox — JavaScript functions are compared by reference, so even two functions with identical bodies are never === to each other unless they’re the exact same object. Most of the time that’s harmless: nothing checks function identity, so a fresh function every render costs nothing anyone notices.

It stops being harmless the moment something downstream depends on that identity staying stable. Two cases dominate: passing the function as a prop to a child wrapped in React.memo (covered in the next lesson, where a new function reference defeats the memoization check even though the function does the same thing), and putting the function in another hook’s dependency array, such as useEffect, where a fresh reference every render would make that effect re-run every render too.

The same dependency-array discipline as useEffect

Both hooks share the exact discipline you learned with useEffect: the dependency array must list every value from the surrounding scope that the function or calculation actually reads. Leave one out, and React keeps handing back the old, memoized result even after the real value has moved on — a silent, stale bug that’s often harder to spot than a crash, because the component still renders, it just renders the wrong thing. ESLint’s react-hooks plugin flags missing dependencies for exactly this reason, and resisting the urge to silence that warning is the right default for both useMemo and useCallback, same as for useEffect.

The other shared discipline is restraint. Neither hook changes whether or how often a component re-renders — only whether a specific value or function gets recomputed within a render that was already going to happen. Reaching for useMemo or useCallback on every value “just in case” adds real overhead (the dependency comparison, the extra closure) for a payoff that, absent an expensive calculation or a memoized consumer downstream, never arrives. The next lesson gives that consumer a name: React.memo, which is often the actual reason useCallback is worth using at all.

What the video covers

Tapas Adhikary’s episode covers both hooks together and spends real time on the framing this lesson leads with: not just the mechanics, but when they’re worth reaching for versus when they add overhead for nothing. It walks through worked examples of an expensive computation wrapped in useMemo and a stable callback passed to a child, with the dependency array behavior demonstrated live. At nearly 25 minutes it’s the longest video in this roadmap group, so the sections above are written to stand on their own if you’d rather skim the video for the live demos and come back here for the reasoning.

Where this fits

With both hooks in hand, the next lesson covers the component-level tool that actually uses a stable prop reference to skip a render entirely: React.memo and component memoization.

Check yourself

  1. 01What does useMemo actually cache?

    The return value of a calculation. On every re-render, React checks the dependency array, and only re-runs the calculation function and stores a new value if one of the dependencies changed; otherwise it hands back the value it already has.

  2. 02Why would wrapping a cheap calculation in useMemo make a component slower rather than faster?

    useMemo itself has a cost: storing the previous dependencies and value, and comparing the new dependencies against them on every render. If the wrapped calculation is cheaper than that bookkeeping, the hook adds overhead without saving any meaningful work.

  3. 03What problem does useCallback solve that useMemo does not?

    useCallback returns the same function reference across re-renders when its dependencies are unchanged, rather than caching a computed value. That stable reference matters when a function is passed to a memoized child component or placed in another hook's dependency array, where a brand-new function identity every render would defeat the memoization or re-trigger an effect.

  4. 04What happens if a value used inside a useMemo calculation is left out of its dependency array?

    The calculation keeps returning its old, memoized value even after that value has changed, because React only recomputes when something in the dependency array itself changes. The result is a stale value that silently fails to update, the same class of bug as an incomplete useEffect dependency array.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark