Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 132 ยท Hooks

useMemo and useCallback

Learn what useMemo and useCallback do in React, when memoization actually helps (expensive work, referential equality), when it doesn't, and how the React Compiler changes the picture.

useMemo and useCallback are the two most over-used hooks in React. Many codebases wrap everything in them "for performance", which makes the code harder to read and usually changes nothing measurable. Used well, though, they are precise tools for two specific problems: skipping a calculation that is truly expensive, and keeping the identity of an object or function stable so other code can tell it has not changed.

This lesson explains what they do, proves with render and computation counts when they help and when they don't, and ends with the modern view: the React Compiler can add this memoization for you, so the hooks are an optimization to reach for after measuring, not a default.

What memoization means

To memoize is to remember the result of a function call and reuse it when called again with the same inputs. React gives you two hooks for it:

JSX
const value = useMemo(() => calculate(a, b), [a, b]);
const handler = useCallback((event) => doSomething(a, event), [a]);
  • useMemo(fn, deps) calls fn during render, stores the result, and on later renders returns the stored result unless a dependency changed (compared with Object.is, as with effects).
  • useCallback(fn, deps) stores the function itself. It is exactly useMemo(() => fn, deps).

So useCallback does not "make a function faster" or prevent it from being created: the inline function expression is still created on every render (JavaScript always evaluates it). What you gain is that React hands you the previous function object back when the dependencies are the same, so its identity is stable.

Both hooks take a dependency array and follow the same honesty rules as effect dependencies: list everything reactive that the function reads.

React treats memoization as a performance hint, not a semantic guarantee. In the future it may discard cached values (for example, to free memory). Your code must be correct if the calculation runs again. Never use useMemo to make something happen only once.

Use 1: skipping an expensive calculation

Components re-render for many reasons that have nothing to do with your expensive work: a parent updates, an unrelated piece of state changes. If a calculation inside the component is slow and its inputs did not change, you can skip it.

The demo filters a list of numbers. We count how often the filter runs (in the console) instead of timing it. One component recalculates in render, the other memoizes. Both receive the same query, and a separate "dark" toggle changes something unrelated.

Counting how often a calculation runs

On load, both log once. Press "Toggle dark": only plain: filtering ... appears; the memoized list found its query unchanged and returned the saved array. Type in the query box and both recalculate, because the dependency really changed. That is the correct behaviour: memoization removes redundant work, never needed work.

How to decide whether a calculation is expensive

Don't guess. Time it in development (console.time, or the Profiler in Profiling and Debugging Performance) with CPU throttling on a realistic device. A good rule of thumb: a loop over a few hundred items that does simple work is not expensive. Thousands of items with non-trivial work per item, or a heavy operation like sorting and grouping large data, may be. If the calculation takes under about a millisecond, memoizing costs more (storing, comparing dependencies) than it saves.

Also ask first whether the work should happen at all: filter on the server, paginate, or virtualize the list.

Use 2: stable identity for memo'd children and effects

The second job has nothing to do with computation cost. In JavaScript {} === {} is false and () => {} === () => {} is false. A component that creates an object or function in its body creates a new one every render. Most of the time nobody cares. It matters when the value is passed to something that compares by identity:

  • a child wrapped in React.memo, which skips re-rendering when props are shallowly equal, (memo and Referential Equality);
  • another hook's dependency array (useEffect, useMemo, useCallback).
A memo child defeated by an inline function

Press "Re-render App" once. The console shows App rendered (count = 1) and then only Row "inline function" rendered. The row that received stableSelect was skipped because both of its props were identical to last time; the row that received unstableSelect got a new function and rendered again, despite being wrapped in memo. Note that useCallback alone does nothing visible here: it only pays off together with something that compares identity, like memo.

The callback only calls setSelected, a state setter that React guarantees is stable, so useCallback can have an empty dependency array. If the callback read count, you would have to list it, and the callback would change whenever count did.

Memoizing objects and arrays

The same applies to values you pass down:

JSX
// New object every render: breaks memo(Chart), re-runs effects that depend on it
const chartOptions = { smooth: true, color: theme.accent };

// Stable while theme.accent is unchanged
const chartOptions = useMemo(() => ({ smooth: true, color: theme.accent }), [theme.accent]);

If an object has no reactive inputs, move it outside the component instead: a module-level constant is stable for free, with no hook at all.

When memoization does not help

Memoization has a cost: extra code, a stored value, a dependency comparison on every render. It only pays when it prevents more work than it adds. Common cases where it is wasted:

  1. Props passed to ordinary (non-memo) components. A child without memo re-renders whenever its parent does, whatever its props are. The demo below proves it:
useCallback without memo prevents nothing

Every press of "Re-render" logs PlainRow rendered, although its only prop is perfectly stable. Memoizing the handler bought nothing, because the child never checked its props.

  1. Cheap calculations. useMemo(() => a + b, [a, b]) is slower than a + b.
  2. Values that change every render anyway. If a dependency is itself unstable (an object created inline, a function from a parent), the memo recomputes every time and is pure overhead.
  3. Event handlers passed to DOM elements. <button onClick={...}> does not care about handler identity.
  4. Components that render fast and rarely. Fix slow renders by finding the cause (see below) rather than sprinkling hooks.

Before adding memoization, try the structural fixes. They often make it unnecessary:

  • Move state down: keep state in the smallest component that uses it, so unrelated siblings are not in its render path.
  • Pass children as props: a wrapper that receives children from above re-renders without re-creating them.
  • Derive instead of store, so there is less to recalculate.

These are covered in memo, Referential Equality and Avoiding Re-renders.

Memoization and StrictMode

In development, StrictMode calls your useMemo calculation function twice on the same render to help you detect impurities. In production it runs once. This also shows why the function must be pure: it must not mutate anything or depend on something other than its listed inputs.

StrictMode runs the useMemo function twice

The console shows summing 3 rows twice on load (the double call), and nothing more when you press "Re-render": rows is the same constant array, so the stored value is reused. If the callback had a side effect, such as pushing into an outside array, the double call would reveal it immediately.

Dependencies: the same rules as effects

All of the earlier advice about honest dependency arrays applies. A memo that lists too few dependencies returns stale results; one that lists unstable dependencies never caches.

JSX
// Bug: the callback closes over `discount` but does not list it
const priceLabel = useCallback(() => '$' + (price - discount), [price]);

// Correct
const priceLabel = useCallback(() => '$' + (price - discount), [price, discount]);

The same react-hooks/exhaustive-deps lint rule checks useMemo and useCallback. A trick for functions that need the latest state without being recreated is a functional update (setItems((items) => [...items, item])), which removes items from the dependency list.

The React Compiler changes the default

Writing useMemo and useCallback by hand is tedious and easy to get wrong, so the React team built the React Compiler, a build-time tool that analyzes your components and inserts memoization automatically, at a finer granularity than you would write by hand, including after early returns where hooks cannot go.

JSX
// What you write
function ProductList({ products, onAdd }) {
  const visible = products.filter((p) => p.inStock);
  return visible.map((p) => <Item key={p.id} product={p} onAdd={() => onAdd(p.id)} />);
}

// What the compiler conceptually produces: filtered list and each callback are cached
// and reused while products / onAdd are unchanged (the real output is lower-level code).

(This snippet is read-only: the compiler is a build step and is not available in our editor. It only works when your code follows the Rules of React, such as pure rendering and no mutation of props or state.)

What this means for you:

  • In a project using the compiler, you do not need to add useMemo/useCallback for performance. Write straightforward code and let the compiler memoize.
  • The hooks are still valid, and still useful as an escape hatch when you need precise control, for instance a value used as an effect dependency, where an exact identity guarantee matters.
  • Without the compiler, apply the guidelines in this lesson: measure first, then memoize.

The compiler is the subject of The React Compiler. The key take-away: understanding memoization is still important, because it teaches you why components re-render, which is what you debug in every codebase.

A practical decision list

  1. Is something actually slow or janky? Measure with the Profiler. If not, stop.
  2. Can you move state down, pass children, or reduce the data? Do that first.
  3. Is a specific calculation slow and recalculated for unrelated updates? Use useMemo around exactly that calculation.
  4. Is a prop causing a memo child to re-render pointlessly, or an effect to re-run? Stabilize that single value with useMemo/useCallback (or hoist it out of the component).
  5. Using the React Compiler? Skip all of the above unless the profiler still shows a problem.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does useCallback(fn, deps) return?

    useCallback caches the function itself, equivalent to useMemo(() => fn, deps). The function is still created each render, but React returns the previous one if the dependencies match.
  2. 2. A parent passes a useCallback-wrapped handler to a child that is NOT wrapped in memo. The parent re-renders. Does the child re-render?

    Without memo the child never compares props, so the stable handler prevents nothing. useCallback pays off together with memo or when the function is a dependency.
  3. 3. Which is the best use of useMemo?

    useMemo is for skipping genuinely expensive calculations whose inputs did not change. Trivial math is cheaper than the memo, and it is a hint, not a once-only guarantee.
  4. 4. Why does a StrictMode development build call a useMemo calculation function twice?

    React double-invokes functions that must be pure so side effects and mutations show up during development.
  5. 5. With the React Compiler enabled, what is the recommended default for performance memoization?

    The compiler inserts fine-grained memoization automatically. useMemo and useCallback remain as an escape hatch.

Summary

  • useMemo caches a calculated value and useCallback caches a function; both recompute only when a dependency changes by Object.is.
  • Memoize to skip genuinely expensive work, or to keep the identity of an object or function stable for a memo child or a hook's dependency list.
  • useCallback alone prevents nothing for ordinary children, and memoizing cheap values costs more than it saves.
  • Memoization is a hint, not a guarantee; the calculation must be pure and correct if it runs again, and StrictMode runs it twice in development.
  • Try restructuring first (move state down, pass children, derive values), and measure before and after.
  • The React Compiler can add memoization automatically; the hooks remain as an escape hatch.

Next: useLayoutEffect, useId, useDebugValue and useInsertionEffect