Skip to content

Search

Articles, tools, solutions and knowledge base guides

Start typing to search across articles, tools and apps.

React useMemo vs useCallback vs memo: When Does Memoization Improve Performance?

Opening a panel or changing the theme makes a large invoice list render again even though the data is unchanged. Adding useMemo everywhere will not automatically fix it. Identify whether the cost comes from calculations, child rendering or changing references. The examples below show how to choose an optimization, preserve correct behavior and measure its effect.

Published Written by Reading time 7 min read
On this page Contents: quick navigation between sections

useMemo: when is caching a calculation worthwhile?

import { useMemo, useState } from "react";

function calculateTotal(invoices, currency) {
  return invoices.reduce((total, invoice) => {
    if (invoice.currency !== currency || !invoice.paid) {
      return total;
    }

    return total + invoice.amountInCents;
  }, 0);
}

export function InvoiceSummary({ invoices, currency }) {
  const [showDetails, setShowDetails] = useState(false);

  const totalInCents = useMemo(() => {
    return calculateTotal(invoices, currency);
  }, [invoices, currency]);

  return (
    <section>
      <output>{totalInCents} cents ({currency})</output>
      <button
        type="button"
        aria-expanded={showDetails}
        onClick={() => setShowDetails((previous) => !previous)}
      >
        Toggle details
      </button>
      {showDetails && <p>Only paid invoices are included.</p>}
    </section>
  );
}

useMemo retains a pure calculation result across renders while its dependencies compare equal using Object.is. The paid invoice total depends on the array and currency, not on the details panel. Opening that panel need not repeat the sum if the array reference is stable. [1]

Avoid caching trivial addition or property reads without a reason. The initial calculation still runs, and subsequent renders pay for dependency checks and retained results. The example uses integer hundredths of currencies such as EUR and USD, without converting currencies. Input amounts and totals must stay within the safe integer range.

memo and useCallback: why does a child still render?

import { memo, useCallback, useState } from "react";

const InvoiceRow = memo(function InvoiceRow({ id, label, onOpen }) {
  return (
    <li>
      <button type="button" onClick={() => onOpen(id)}>
        {label}
      </button>
    </li>
  );
});

export function InvoiceList({ invoices }) {
  const [activeId, setActiveId] = useState(null);

  const openInvoice = useCallback((invoiceId) => {
    setActiveId(invoiceId);
  }, []);

  return (
    <section>
      <p>Active invoice: {activeId ?? "None"}</p>
      <ul>
        {invoices.map((invoice) => (
          <InvoiceRow
            key={invoice.id}
            id={invoice.id}
            label={invoice.label}
            onOpen={openInvoice}
          />
        ))}
      </ul>
    </section>
  );
}

memo can skip child rendering when props stay equal; by default each prop is compared with Object.is. useCallback retains a function reference rather than its return value and does not prevent creation of the function passed to it. [2][3]

Changing activeId leaves row IDs, labels and openInvoice unchanged, so rows can skip work. An inline arrow inside the row is not part of its incoming props. If the parent passed onOpen={() => openInvoice(invoice.id)}, every row would receive a fresh reference. A row’s own state or consumed context can still trigger rendering.

Why do dependencies invalidate the cache?

import { useMemo } from "react";

export function PaidInvoiceCount({ invoices, currency }) {
  const count = useMemo(() => {
    const matches = invoices.filter((invoice) => {
      return invoice.paid && invoice.currency === currency;
    });

    return matches.length;
  }, [invoices, currency]);

  return <output>{count}</output>;
}

An object created inside a component has a fresh identity on each render. Using it as a dependency, such as [invoices, options], can invalidate the result even when the fields match. Depend on the actual values needed, such as currency, instead of caching every intermediate object. [1][5]

Do not mutate invoices in place: unchanged identity can leave the cached result stale. Update data immutably and retain unchanged branch references. Never omit dependencies just to increase cache hits. For inexpensive filtering, computing during render without caching is often simpler. [9]

How do you prevent stale closures in useCallback?

import { memo, useCallback, useState } from "react";

const AddButton = memo(function AddButton({ onAdd }) {
  return (
    <button type="button" onClick={onAdd}>
      Add item
    </button>
  );
});

export function CartCounter() {
  const [quantity, setQuantity] = useState(0);

  const addItem = useCallback(() => {
    setQuantity((previous) => previous + 1);
  }, []);

  return (
    <section>
      <output>{quantity}</output>
      <AddButton onAdd={addItem} />
    </section>
  );
}

A callback with empty dependencies that reads quantity from its render can keep using the initial value. Removing a dependency to keep a function stable changes its behavior. [2][5]

When the next state depends only on the previous state, use a functional updater. Here addItem never reads quantity, so empty dependencies are correct. If a callback also reads a current limit, identifier or other reactive input, include that input in the dependency list.

Why does memo not stop context updates?

import { createContext, memo, useContext, useState } from "react";

const ThemeContext = createContext("light");

const InvoiceDetails = memo(function InvoiceDetails({ invoiceId }) {
  return <p>Invoice: {invoiceId}</p>;
});

function ThemedInvoice({ invoiceId }) {
  const theme = useContext(ThemeContext);

  return (
    <section data-theme={theme}>
      <InvoiceDetails invoiceId={invoiceId} />
    </section>
  );
}

export function InvoicePage({ invoiceId }) {
  const [theme, setTheme] = useState("light");

  function toggleTheme() {
    setTheme((previous) => (previous === "light" ? "dark" : "light"));
  }

  return (
    <ThemeContext.Provider value={theme}>
      <button type="button" onClick={toggleTheme}>
        Toggle theme
      </button>
      <ThemedInvoice invoiceId={invoiceId} />
    </ThemeContext.Provider>
  );
}

A context consumer reacts to a changed provider value even when wrapped in memo. In the example the wrapper reads the theme, while the memoized invoice details receive only an ID. The details can therefore skip work on theme changes. [3][4]

Avoid creating a new context object unnecessarily. Separate independent contexts if their values change at different rates. Do not blindly add deep prop comparison: a custom comparator must account for functions too, otherwise children may invoke stale closures. Comparing large structures may cost more than rendering. [3]

How do you measure the benefit with React Profiler?

import { Profiler, useState } from "react";

function logRender(id, phase, actualDuration, baseDuration) {
  console.log({
    id,
    phase,
    actualDuration,
    baseDuration,
  });
}

export function ProfileScenario({ ListComponent, invoices }) {
  const [expanded, setExpanded] = useState(false);

  return (
    <section>
      <button
        type="button"
        aria-expanded={expanded}
        onClick={() => setExpanded((previous) => !previous)}
      >
        Toggle summary
      </button>
      {expanded && <p>Invoice overview</p>}
      <Profiler id="invoice-list" onRender={logRender}>
        <ListComponent invoices={invoices} />
      </Profiler>
    </section>
  );
}

Run the same interaction and data with a baseline list and an optimized version. Pass a stable ListComponent type from outside the scenario. Toggle the summary repeatedly, then separately change the data. Compare updates rather than mixing them with initial mounts. [6]

actualDuration measures rendering work for the profiled subtree in that update; baseDuration estimates the cost of rendering the whole subtree without skipped work. Neither is full interaction latency. Compare repeated measurements on representative hardware with a profiling-enabled production build. React Performance tracks help locate other delays. Development Strict Mode can distort timings; log counts alone do not establish a speedup. [1][6][8]

React Compiler: is manual memoization still useful?

React Compiler can optimize components, values and functions at build time. Installing React alone does not enable it. In a compiled project, start with straightforward code and profile the result; compilation does not guarantee that every piece of code is optimized. [7]

Manual memoization remains useful in projects without the compiler or where measurements justify explicit control. Do not rely on either hook as permanent storage. React may discard its cache, for example when initial mounting suspends. Correctness must come from state, props and pure calculations, not cached identity. [1][2]

First remove unnecessary updates and narrow the scope of changing state. Use useMemo for costly calculations, memo for costly children with stable props, and useCallback when stable function identity avoids work. Keep dependencies complete and measure before and after. React Compiler can reduce the need for manual optimizations. [7]

React useMemo useCallback memo Memoization React Profiler React Compiler Web Performance

Frequently asked questions

Does useCallback prevent rendering?

Not on its own. A stable function prop can help a memoized child skip work. [2][3]

Should every filter use useMemo?

No. Consider computation cost, update frequency and input stability. [1]

Does memo work with useContext?

Changes to consumed context still update the consumer. [4]

Does React Compiler replace useMemo and useCallback?

It often reduces manual memoization in compiled code. Verify configuration and measurements. [7]

Sources and references

  1. React Documentation: useMemo↩1↩2↩3↩4↩5↩6↩7
  2. React Documentation: useCallback↩1↩2↩3↩4↩5
  3. React Documentation: memo↩1↩2↩3↩4↩5
  4. React Documentation: useContext↩1↩2↩3
  5. React Documentation: exhaustive-deps↩1↩2↩3
  6. React Documentation: Profiler↩1↩2↩3
  7. React Documentation: React Compiler introduction↩1↩2↩3
  8. React Documentation: React Performance tracks↩
  9. React Documentation: You Might Not Need an Effect↩

Was this helpful?

Get new articles by email

One short email per new Learning article. No spam, unsubscribe in one click.

We only use your email to send new articles. No third-party sharing.

Back to Learning