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.
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.
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>
);
}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.