useMemo(() => compute(a, b), [a, b]) caches the result of a calculation between renders and recomputes only when a dependency changes (Object.is). Use it for genuinely expensive computations (filtering or sorting thousands of rows, heavy parsing) and to keep object/array identities stable for memoized children or hook dependencies. It's a performance hint, not a semantic guarantee: React may discard the cache, and in development Strict Mode calls your function twice. With the React Compiler, most manual useMemo calls are unnecessary.
function ProductTable({ products, query, sortKey }) {
const visible = useMemo(() => {
const q = query.toLowerCase();
return products
.filter(p => p.name.toLowerCase().includes(q))
.sort((a, b) => compare(a[sortKey], b[sortKey]));
}, [products, query, sortKey]);
const [hovered, setHovered] = useState(null);
// Hovering re-renders, but `visible` is reused
return <Table rows={visible} onHover={setHovered} />;
}
How do you know it's expensive? Measure it (console.time, or the React Profiler). A rough rule from react.dev: if it consistently takes around 1 ms or more on a slow device, memoizing is reasonable.
const chartOptions = useMemo(() => ({ theme, showLegend: true }), [theme]);
return <MemoChart options={chartOptions} />; // memo(Chart)
Without useMemo, a new object each render defeats memo and re-runs any effect that depends on options.
useMemo to "run something once" or for side effects. Use a ref, state initializer or effect instead.memo on the child, or restructure (move state down, pass children).children. Elements created by the parent don't re-render when the wrapper's state changes.useState(() => parse(raw)).useDeferredValue when the cost is unavoidable but shouldn't block typing.useMemo/useCallback reuse the memoized result from the first render during the second.useMemo for cases the compiler can't handle or where you need explicit control over effect dependencies.Spotted a mistake or a rights concern? Report an issue