Memoization

memo, useMemo and useCallback, and the fixes that beat them.

Builds on Measure first.

Chapter 28 ended with a measurement: typing in the search box re-rendered a stats panel that took 60 ms and didn't use the query at all. It rendered because its parent did. That's React's default, and it's the right default, because rendering is usually cheap and always correct. But when a subtree is expensive and its inputs haven't changed, you want React to skip it.

This chapter covers every way to do that, in the order you should reach for them. First the structural fixes, which cost nothing. Then memo, useMemo and useCallback, with the one idea that makes them work or silently fail: referential equality. Chapter 30 then shows how the React Compiler automates all of it.

The problem: one keystroke, everything renders#

Here's a page with a note field and a slow book table under it. Type in the note. Every <Rendered> box flashes and its counter climbs, including the table that has nothing to do with the note.

Everything re-renders
import { useState } from "react";
import { Rendered, books, slowDown } from "guide-tools";

function BookTable() {
  slowDown(40);
  return (
    <Rendered label="BookTable (40 ms)">
      <ul>{books.slice(0, 4).map((b) => <li key={b.id}>{b.title}</li>)}</ul>
    </Rendered>
  );
}

export default function App() {
  const [note, setNote] = useState("");
  return (
    <Rendered label="App">
      <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="Write a note" />
      <BookTable />
    </Rendered>
  );
}

The input feels sticky because every keystroke runs a 40 ms render before the next frame can paint. As chapter 23 showed, when a component's state changes React re-renders it and, by default, every component it renders, all the way down. It doesn't check whether a child's props changed. Usually that's fine. Here it isn't.

Structural fixes first#

Before any memoization API, look at where the state lives. Two rearrangements fix most cases, cost nothing at runtime and make the code simpler, not more complex.

Move state down#

The note state lives in App, so every change to it re-renders everything App renders. But only the input uses it. Move the state into a component that owns just the input:

Move state down
import { useState } from "react";
import { Rendered, books, slowDown } from "guide-tools";

function BookTable() {
  slowDown(40);
  return (
    <Rendered label="BookTable (40 ms)">
      <ul>{books.slice(0, 4).map((b) => <li key={b.id}>{b.title}</li>)}</ul>
    </Rendered>
  );
}

function NoteInput() {
  const [note, setNote] = useState("");
  return (
    <Rendered label="NoteInput">
      <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="Write a note" />
    </Rendered>
  );
}

export default function App() {
  return (
    <Rendered label="App">
      <NoteInput />
      <BookTable />
    </Rendered>
  );
}

Now only NoteInput renders on each keystroke. The table renders once. No API, no comparison, no dependency arrays. This is react.dev's own advice: don't lift state higher than it needs to be.

Pass the slow part in as children#

Sometimes the state really does belong high up. Say a panel tracks whether it's expanded, and the slow table lives inside it. You can't move the state below the table, because the panel wraps the table. But you can stop the panel from creating the table's element:

Lift the content up: pass children
import { useState, type ReactNode } from "react";
import { Rendered, books, slowDown } from "guide-tools";

function BookTable() {
  slowDown(40);
  return (
    <Rendered label="BookTable (40 ms)">
      <ul>{books.slice(0, 4).map((b) => <li key={b.id}>{b.title}</li>)}</ul>
    </Rendered>
  );
}

function Panel({ children }: { children: ReactNode }) {
  const [highlighted, setHighlighted] = useState(false);
  return (
    <Rendered label="Panel" style={{ outline: highlighted ? "2px solid #b4532a" : "none" }}>
      <button onClick={() => setHighlighted((h) => !h)}>Toggle highlight</button>
      {children}
    </Rendered>
  );
}

export default function App() {
  return (
    <Rendered label="App">
      <Panel>
        <BookTable />
      </Panel>
    </Rendered>
  );
}

Click the button. Panel re-renders, BookTable doesn't. Here's why. <BookTable /> is a React element, a plain object, and it's created by App, not by Panel. When Panel's state changes, React calls Panel again, but App doesn't run, so children is the very same object as last time. When React reconciles a child and finds that its element and props are identical to last time (and it has no pending state or context change), it skips that child entirely. That bailout on identical props is the whole engine behind every technique in this chapter.

  • Move state down when only part of the tree uses it.
  • Pass children (or any JSX prop) when a stateful wrapper surrounds expensive content.
  • Both work because React skips a child whose props object hasn't changed. No API needed.

Referential equality#

The structural fixes work by not creating new props. When you can't avoid re-rendering the parent, you need React to compare the new props with the old ones and skip the child if they're "the same". So what does "the same" mean?

React uses Object.is. For primitives (strings, numbers, booleans, null, undefined) that compares values: Object.is(3, 3) is true. For objects, arrays and functions it compares identity, whether both sides are the very same object in memory. Two objects with identical contents are still different objects.

Same contents, different objects
console.log(Object.is("dune", "dune"));        // true: primitives compare by value
console.log(Object.is({ a: 1 }, { a: 1 }));    // false: two different objects
console.log(Object.is([], []));                // false
console.log(Object.is(() => {}, () => {}));    // false

const options = { dense: true };
console.log(Object.is(options, options));      // true: the same object

function render() {
  // Every call creates a new object and a new function.
  return { options: { dense: true }, onSelect: () => {} };
}
const first = render();
const second = render();
console.log(Object.is(first.options, second.options));   // false
console.log(Object.is(first.onSelect, second.onSelect)); // false
Nothing logged yet.

That last part is the crux. A component is a function, and every render calls it again. Any object, array or function literal written in its body ({ dense: true }, [a, b], () => select(id)) is a brand-new value on every render. Pass one as a prop and the child can never see "the same props".

Build it: a toy memo#

Before the real API, here's the idea in a few lines. A wrapper component remembers the last props it saw and the element it produced. If every prop is Object.is-equal to last time, it returns the same element object, and React's identical-props bailout skips the wrapped component, exactly as it did with children above.

A homemade memo
import { useRef, useState, type ComponentType } from "react";
import { Rendered, slowDown } from "guide-tools";

function shallowEqual(a: Record<string, unknown>, b: Record<string, unknown>) {
  const ka = Object.keys(a);
  const kb = Object.keys(b);
  return ka.length === kb.length && ka.every((k) => Object.is(a[k], b[k]));
}

// A toy. It reads and writes a ref during render, which real code
// shouldn't do. React's memo does this check inside the reconciler.
function toyMemo<P extends Record<string, unknown>>(Component: ComponentType<P>) {
  return function Memoized(props: P) {
    const last = useRef<{ props: P; element: JSX.Element } | null>(null);
    if (!last.current || !shallowEqual(last.current.props, props)) {
      last.current = { props, element: <Component {...props} /> };
    }
    return last.current.element;
  };
}

function Greeting({ name }: { name: string }) {
  slowDown(30);
  return <Rendered label="Greeting (30 ms)">Hello, {name}</Rendered>;
}

const FastGreeting = toyMemo(Greeting);

export default function App() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState("Ada");
  return (
    <Rendered label="App">
      <button onClick={() => setCount(count + 1)}>Unrelated: {count}</button>
      <button onClick={() => setName(name === "Ada" ? "Grace" : "Ada")}>Change name</button>
      <FastGreeting name={name} />
    </Rendered>
  );
}

Click Unrelated and Greeting stays put. Click Change name and it renders, because name changed. Now imagine passing style={{ color: "red" }} to FastGreeting: shallowEqual would fail on every render, and the toy would be pure overhead. Keep that in mind; the real memo behaves the same way.

memo: skip a component when its props are equal#

const MemoizedTable = memo(BookTable);
// or, with a custom comparison
const MemoizedTable = memo(BookTable, (prev, next) => prev.id === next.id);

memo wraps a component so that when its parent re-renders, React compares each new prop with the previous one using Object.is, and skips rendering if all are equal. That's the toy above, done properly inside React. A memoized component still re-renders when its own state changes or when a context it reads changes; memo only concerns props from the parent. And react.dev is explicit that it's a performance hint, not a guarantee: React may still render it.

Here's memo on the reading list, first working, then broken by two innocent-looking props:

memo works, then breaks
import { memo, useState } from "react";
import { Rendered, books, slowDown } from "guide-tools";

type Book = (typeof books)[number];

const BookTable = memo(function BookTable({
  items,
  options,
  onSelect,
}: {
  items: Book[];
  options?: { dense: boolean };
  onSelect?: (id: number) => void;
}) {
  slowDown(40);
  return (
    <Rendered label="BookTable (40 ms)">
      <ul style={{ lineHeight: options?.dense ? 1.2 : 1.8 }}>
        {items.map((b) => (
          <li key={b.id} onClick={() => onSelect?.(b.id)}>{b.title}</li>
        ))}
      </ul>
    </Rendered>
  );
});

export default function App() {
  const [note, setNote] = useState("");
  const [selected, setSelected] = useState<number | null>(null);
  return (
    <Rendered label="App">
      <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="Write a note" />
      <p>Selected: {selected ?? "none"}</p>

      {/* 1. Works: `books` is the same array on every render. */}
      <BookTable items={books} />

      {/* 2. Broken: a new object and a new function on every render.
          Uncomment to see the counter climb again. */}
      {/* <BookTable items={books} options={{ dense: true }} onSelect={(id) => setSelected(id)} /> */}
    </Rendered>
  );
}

With only the first table, typing doesn't re-render it: items is the module-level books array, the same object every time. Comment the first one out and uncomment the second. Now the counter climbs on every keystroke: options and onSelect are new values on every render of App, so memo compares, finds a difference, and renders anyway. You pay for the comparison and the render.

Why an inline object breaks memo
Parent, render 1options = {dense} #1onSelect = fn #1memo comparesfirst render:nothing to comparememo(Table)rendersHook slots on the parent's fibernone: values are recreatedon every render
Step 1 of 5

Render 1. The parent creates an options object (#1) and an onSelect function (#1) and passes them to memo(Table). Table renders, and memo remembers these props.

useMemo and useCallback: keep the same value between renders#

To pass an object or function to a memoized child without breaking it, the parent has to hand over the same object while nothing relevant changed. That's what these two hooks do.

const options = useMemo(() => ({ dense: true }), []);
const onSelect = useCallback((id: number) => setSelected(id), []);

useMemo(calculate, deps) calls calculate on the first render and stores the result, together with the dependency values, in a slot on the component's fiber (the same place useState keeps its state, chapter 8). On later renders it compares each dependency with Object.is. If none changed, it returns the stored result; otherwise it recalculates. useCallback(fn, deps) is exactly useMemo(() => fn, deps): it caches the function itself, not its result.

Both serve two purposes:

  1. Stable references, so a memo child or an effect's dependency array sees the same object when nothing changed. This is what fixes the broken table.
  2. Skipping an expensive calculation, such as filtering and sorting thousands of rows, when its inputs haven't changed.

Here's the second use. Sorting is artificially slow, and the note input shouldn't pay for it:

useMemo skips a slow calculation
import { useMemo, useState } from "react";
import { books, slowDown } from "guide-tools";

function sortBooks(by: "title" | "year") {
  console.log("sorting by", by);
  slowDown(50);
  return [...books].sort((a, b) =>
    by === "year" ? a.year - b.year : a.title.localeCompare(b.title)
  );
}

export default function App() {
  const [note, setNote] = useState("");
  const [by, setBy] = useState<"title" | "year">("title");
  const sorted = useMemo(() => sortBooks(by), [by]);
  return (
    <div>
      <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="Write a note" />
      <button onClick={() => setBy(by === "title" ? "year" : "title")}>Sort by {by === "title" ? "year" : "title"}</button>
      <ol>{sorted.map((b) => <li key={b.id}>{b.title} ({b.year})</li>)}</ol>
    </div>
  );
}
Nothing logged yet.

Typing in the note logs nothing: by didn't change, so useMemo returns the cached array. Clicking the sort button logs once and pays the 50 ms. Replace the useMemo line with const sorted = sortBooks(by); and every keystroke logs and stutters.

Two details from the docs worth knowing. useMemo doesn't make the first render faster, only later ones. And it's a performance optimization, not a semantic guarantee: React may throw the cached value away (for example, if the component suspends during its initial mount), so your code must still be correct if the calculation runs again. If you need a value to persist, that's state or a ref.

When they help, and when they waste effort#

Memoization isn't free. Each memo compares every prop on every parent render. Each useMemo and useCallback allocates a dependency array, compares it, and keeps the old value in memory. And all of it adds code with dependency arrays that can be wrong.

It earns its keep when:

  • A component re-renders often with the same props and its render is measurably slow (chapter 28: measure it).
  • A calculation is slow and its inputs rarely change. react.dev's rule of thumb: if it adds up to about 1 ms or more, consider memoizing; unless you're looping over thousands of items, it probably isn't slow.
  • A value is passed to a memo component or used as a dependency of another hook (an effect, another useMemo), where a new identity on each render causes real extra work.

It wastes effort when:

  • The component is cheap. Comparing props can cost as much as rendering.
  • Any single prop is new on every render. One inline object, array, function or JSX child and the whole memo is dead weight.
  • useCallback wraps a function passed to a component that isn't memoized. The child re-renders anyway, so the stable reference buys nothing.
  • useMemo wraps something trivial like a + b or a ten-item filter.

Fix the reading list#

Fix itStop the table from re-rendering

BookTable is already wrapped in memo, but typing in the note still re-renders it every time. Make typing in the note leave the table alone, while clicking a book still updates "Selected: …". Any correct approach is fine: memoization hooks or a structural fix. Press Check when it works.

import { useState } from "react";
import { books } from "guide-tools";
import { BookTable } from "./BookTable";

export default function App() {
  const [note, setNote] = useState("");
  const [selected, setSelected] = useState<string>("none");
  const sorted = [...books].sort((a, b) => a.year - b.year).slice(0, 4);
  return (
    <div>
      <input aria-label="note" value={note} onChange={(e) => setNote(e.target.value)} placeholder="Write a note" />
      <p>Selected: {selected}</p>
      <BookTable
        items={sorted}
        options={{ dense: true }}
        onSelect={(title) => setSelected(title)}
      />
    </div>
  );
}

Pitfalls#

Check your understanding#

Predictmemo and children

Card is memo(function Card({ children }) { ... }), and it's expensive. The parent renders <Card><Avatar user={user} /></Card> and re-renders whenever an unrelated counter changes. Does Card re-render when the counter changes? What would you change?

Quick checkDoes useCallback help here?

A parent passes onClick={useCallback(() => setOpen(true), [])} to a plain, non-memoized <Button>. The parent re-renders often. What does the useCallback achieve?

Quick checkCheapest fix

A Layout component keeps a sidebarOpen boolean in state and renders <Sidebar /> and an expensive <Feed /> directly. Toggling the sidebar re-renders Feed. What's the cheapest correct fix?

Explain it out loudmemo, useMemo and useCallback

An interviewer asks: "What's the difference between memo, useMemo and useCallback, and when would you use them?" Answer in about a minute.

Interview angle

Say it in 30 seconds

When a component re-renders, React re-renders its children by default. It only skips a child when the child's props object is identical, or when the child is wrapped in memo and every prop is Object.is-equal to last time. Objects and functions compare by identity, so anything created inline in render is new every time and defeats memo; useMemo and useCallback keep the same value between renders while their dependencies don't change. I reach for structural fixes first, moving state down or passing children, because they cost nothing, and I memoize only what profiling shows is slow.

What's the difference between memo, useMemo and useCallback?

basic

Why does passing an inline object or arrow function break React.memo?

basic

How can you avoid unnecessary re-renders without memo, useMemo or useCallback?

intermediate

When does memoization waste effort, or make things worse?

intermediate

A component is wrapped in memo and its props haven't changed. Can it still re-render?

intermediate

Can you rely on useMemo to keep a value, for example to make sure an effect runs only once?

senior

What are the risks of passing a custom comparison function to memo?

senior

Recap#

  • By default a parent's render re-renders every child. React skips a child only when its props object is identical, or when memo finds every prop Object.is-equal.
  • Try structural fixes first: move state down to where it's used, or pass expensive content in as children so the stateful parent doesn't create it.
  • Object.is compares objects and functions by identity, so inline objects, arrays, functions and JSX children are new on every render and break memo.
  • useMemo caches a value and useCallback caches a function between renders, keyed on dependencies. They matter for slow calculations, memo props and hook dependencies, and are wasted effort elsewhere.
  • Measure before and after. Chapter 30's React Compiler does this memoization automatically, at a finer grain than you would by hand.

Sources#