Skip to content
jshacks.dev
Frameworks

Memoize an expensive calculation with useMemo

Cache the result of a costly computation between React renders with useMemo, and recompute it only when its dependencies change.

1 min read
Summarize in AI

A component that filters and sorts a big list on every keystroke repeats the same work when something unrelated changes. useMemo remembers the result until its inputs change.

src/ProductList.jsxJSX
import { useMemo, useState } from 'react';

export function ProductList({ products }) {
  const [query, setQuery] = useState('');
  const [dark, setDark] = useState(false);

  const visible = useMemo(() => {
    console.log('filtering');
    return products
      .filter((p) => p.name.toLowerCase().includes(query.toLowerCase()))
      .sort((a, b) => a.name.localeCompare(b.name));
  }, [products, query]);

  return (
    <div className={dark ? 'dark' : ''}>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <button onClick={() => setDark(!dark)}>Toggle theme</button>
      <ul>{visible.map((p) => <li key={p.id}>{p.name}</li>)}</ul>
    </div>
  );
}
Text
filtering          (first render)
filtering          (after typing "a")
                   (nothing logged when "Toggle theme" is clicked)

Toggling the theme re-renders the component, but products and query are unchanged, so React returns the stored array. The function runs again only when a dependency changes. This is the behaviour in the useMemo reference.

Treat it as a performance hint, not a guarantee: React may discard the cache. Measure first, since for small lists the memoization costs more than it saves.

Also inFunctions
Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Functions

Write a once function

Write a once function in JavaScript that runs a callback a single time and returns the cached result after that. Works in any Node.js, ES2015 or later.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.