TExcelTAD
Home › React › React useMemo

React useMemo

useMemo caches the result of a calculation between renders. React re-runs the calculation only when one of its dependencies changes; otherwise it hands back the stored result.

jsx
const visibleTodos = useMemo(() => filterTodos(todos, tab), [todos, tab]);

Use it for two things: skipping expensive recalculations, and keeping object or array identity stable for memoized children and effect dependencies.

Skipping expensive work

Below, finding prime numbers is deliberately slow. Without useMemo, every keystroke in the unrelated "note" input would redo the calculation. Turn memoization on and off and compare how responsive typing feels:

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

function primesUpTo(limit) {
  const primes = [];
  for (let n = 2; n <= limit; n++) {
    let isPrime = true;
    for (let d = 2; d * d <= n; d++) {
      if (n % d === 0) { isPrime = false; break; }
    }
    if (isPrime) primes.push(n);
  }
  // pretend this is even heavier
  const start = performance.now();
  while (performance.now() - start < 150) {}
  return primes;
}

export default function App() {
  const [limit, setLimit] = useState(5000);
  const [note, setNote] = useState('');
  const [memoOn, setMemoOn] = useState(true);

  const memoized = useMemo(() => (memoOn ? primesUpTo(limit) : null), [limit, memoOn]);
  const primes = memoOn ? memoized : primesUpTo(limit);

  return (
    <div>
      <label><input type="checkbox" checked={memoOn} onChange={(e) => setMemoOn(e.target.checked)} /> useMemo on</label>
      <p>
        Limit: <input type="number" step={1000} value={limit} onChange={(e) => setLimit(Number(e.target.value))} />
      </p>
      <p>
        Note (unrelated): <input value={note} onChange={(e) => setNote(e.target.value)} placeholder="type quickly here" />
      </p>
      <p>{primes.length} primes up to {limit}; the largest is {primes.at(-1)}.</p>
    </div>
  );
}

With useMemo on, typing a note is instant; with it off, every keystroke waits for the 150 ms calculation.

Measuring before memoizing

Don't guess — measure. Wrap a calculation with console.time to see what it costs:

jsx
console.time('filter');
const visible = filterTodos(todos, tab);
console.timeEnd('filter');   // filter: 0.12ms → not worth memoizing

As a rule of thumb, calculations that take 1 ms or more in a production build may be worth caching. Most filtering and mapping of a few hundred items is far cheaper.

Stable objects for dependencies

An object literal created during render is a new object every time. If it's an effect dependency, the effect re-runs on every render. useMemo keeps the same object while its inputs are unchanged:

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

export default function App() {
  const [city, setCity] = useState('Hanoi');
  const [units, setUnits] = useState('metric');
  const [darkMode, setDarkMode] = useState(false);

  const options = useMemo(() => ({ city, units }), [city, units]);

  useEffect(() => {
    console.log(`(re)connecting weather feed: ${options.city}, ${options.units}`);
  }, [options]);

  return (
    <div style={{ background: darkMode ? '#222' : '#fff', color: darkMode ? '#eee' : '#222', padding: 12 }}>
      <select value={city} onChange={(e) => setCity(e.target.value)}>
        <option>Hanoi</option><option>Tokyo</option><option>Paris</option>
      </select>{' '}
      <select value={units} onChange={(e) => setUnits(e.target.value)}>
        <option value="metric">°C</option><option value="imperial">°F</option>
      </select>{' '}
      <label><input type="checkbox" checked={darkMode} onChange={(e) => setDarkMode(e.target.checked)} /> dark mode</label>
      <p>Toggling dark mode re-renders, but does not reconnect.</p>
    </div>
  );
}

Without useMemo, toggling dark mode would log a reconnect every time. (An even simpler fix here: depend on city and units directly instead of an object.)

Memoizing derived lists for memo children

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

const CONTACTS = ['An', 'Bich', 'Cuong', 'Dung', 'Giang', 'Hai', 'Khoa', 'Linh', 'Mai', 'Nam'];
let listRenders = 0;

const ContactList = memo(function ContactList({ contacts }) {
  listRenders += 1;
  return (
    <ul>
      {contacts.map((c) => <li key={c}>{c}</li>)}
      <small>List rendered {listRenders}×</small>
    </ul>
  );
});

export default function App() {
  const [filter, setFilter] = useState('');
  const [clock, setClock] = useState(0);

  const filtered = useMemo(
    () => CONTACTS.filter((c) => c.toLowerCase().includes(filter.toLowerCase())),
    [filter]
  );

  return (
    <div>
      <input value={filter} onChange={(e) => setFilter(e.target.value)} placeholder="Filter contacts" />{' '}
      <button onClick={() => setClock(clock + 1)}>Unrelated update ({clock})</button>
      <ContactList contacts={filtered} />
    </div>
  );
}

The "unrelated update" button re-renders App, but filtered keeps the same array reference, so the memoized ContactList skips rendering.

Rules and pitfalls

Rule Detail
The calculation must be pure no state updates, requests or mutations inside
List all values used missing dependencies give stale results
It's a performance hint React may discard the cache (e.g. during development edits); code must still work without it
Don't memoize everything each useMemo costs memory and a dependency comparison

Tip: Often you can avoid useMemo by moving work out of the component: constants at module level, calculations in event handlers, or state lifted lower so fewer components re-render.

Test yourself

When does useMemo(() => compute(a), [a]) call compute again?

  1. On every render
  2. Only when a changes (and on the first render)
  3. Never after the first render
  4. When the component unmounts

Which is a good reason to use useMemo?

  1. To run side effects after render
  2. To cache a slow calculation or keep an object reference stable
  3. To store a DOM node
  4. To replace useState

What must the function passed to useMemo be?

  1. async
  2. pure
  3. a component
  4. a reducer