What is useMemo?
useMemo(compute, deps) caches the result of a calculation between renders and recomputes it only when a dependency changes. Use it to skip expensive computations, or to keep an object or array reference stable for memoized children and effect dependencies. With the React Compiler, most manual useMemo calls become unnecessary.
When it helps
- Expensive work: filtering or sorting thousands of rows, parsing, heavy math. Measure first: if it takes under about 1ms, memoizing usually is not worth it.
- Referential stability: objects or arrays passed to a
React.memochild or used in auseEffectdependency array.
When it does not help
- Cheap calculations: the comparison and storage overhead can exceed the work.
- Values that change every render anyway.
- As a semantic guarantee: React may discard the cache (for example during development, or for offscreen content), so code must work correctly without it.
Rules
- Pure function, no side effects.
- List every reactive value used inside in
deps. - Called at the top level like any hook.
React Compiler (1.0)
The compiler automatically memoizes values and JSX at build time with finer granularity than hand-written useMemo. Projects using it can remove most useMemo calls; the docs keep useMemo as an escape hatch, for example to control an effect's dependencies precisely.
Better alternatives first
Often the fix is structural: move state down so fewer components re-render, or pass JSX as children.
Code example
1import { memo, useMemo, useState } from "react";23type Row = { id: number; name: string; score: number };45const Chart = memo(function Chart({ data }: { data: Row[] }) {6 console.log("Chart rendered");7 return <p>Chart with {data.length} points</p>;8});910export function Leaderboard({ rows }: { rows: Row[] }) {11 const [query, setQuery] = useState("");12 const [darkMode, setDarkMode] = useState(false);1314 // Recomputed only when rows or query change, not when darkMode toggles15 const visible = useMemo(() => {16 const q = query.toLowerCase();17 return rows.filter((r) => r.name.toLowerCase().includes(q)).toSorted((a, b) => b.score - a.score);18 }, [rows, query]);1920 return (21 <div className={darkMode ? "dark" : ""}>22 <input value={query} onChange={(e) => setQuery(e.target.value)} />23 <button onClick={() => setDarkMode((d) => !d)}>Theme</button>24 <Chart data={visible} /> {/* stable reference: no re-render on theme toggle */}25 </div>26 );27}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.