useMemo caches the computed result of a function between re-renders. During each render, React checks the dependency array; if none of the values changed, React reuses the saved result instead of running a slow sort, filter, or aggregation again.
useMemo solves two distinct problems: skipping heavy CPU work (like filtering 10,000 table rows) and keeping a derived object or array's memory reference stable when passing it to a React.memo child or useEffect.
import { useMemo, useState } from 'react';
export function ProductCatalog({ products }) {
const [query, setQuery] = useState('');
const [darkMode, setDarkMode] = useState(false);
const visibleProducts = useMemo(() => {
const term = query.trim().toLowerCase();
return products
.filter((item) => item.name.toLowerCase().includes(term))
.sort((a, b) => a.price - b.price);
}, [products, query]);
return (
<section className={darkMode ? 'dark' : 'light'}>
<input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Filter..." />
<button type="button" onClick={() => setDarkMode((d) => !d)}>Toggle Theme</button>
<p>Showing {visibleProducts.length} items</p>
</section>
);
}
Toggling darkMode re-renders ProductCatalog, yet visibleProducts does not re-filter or re-sort because products and query stayed unchanged.
useMemo Mistakesa + b or formatting a short string in useMemo wastes memory and hurts readability because running the dependency check costs more than the calculation itself.useMemo: useMemo runs during rendering and must remain pure. Never call state setters, DOM mutations, or fetch inside useMemo.useMemo as a Permanent Cache: React may discard cached values to free memory in future concurrent features, so only use useMemo as a performance optimization, not for correctness.useMemo?Measure it with console.time or the React DevTools Profiler. Generally, calculations taking under 1 millisecond do not need manual useMemo.
useMemo stabilize a Context Provider's value object?Yes. Wrapping useMemo(() => ({ user, logout }), [user]) prevents unnecessary re-renders across every consumer whenever the Provider's parent updates.
[])?React computes the value once when the component mounts and keeps returning that exact value until the component unmounts.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With