All visualizationsReact · 17 of 18
useMemo — the answer shelf (a work counter proves it)
Three renders: the plain filter pays 3 times, the memoized one pays once — and honestly re-pays when a dependency truly changes.
💡
THE BIG IDEA
React.memo (lesson 9) skips re-RENDERS; useMemo skips re-COMPUTATIONS — the expensive filter that keeps re-running because an unrelated counter changed. We build useMemo in five lines out of parts you already own (a shelf slot + deps compared with ===), instrument the expensive function with a work counter, and let the printed ledger make the case — including the honest cost when dependencies really change.
Move your mouse over any line to see what it does. Hover a loop line and it plays through every repeat. Or press ▶ Play to watch the whole thing. On a phone, tap the arrows.
1let work = 0;
2const filterJobs = (jobs, city) => {
3 work++;
4 return jobs.filter((j) => j === city).length;
5};
6const jobs = ["chennai", "pune", "chennai"];
7for (let r = 1; r <= 3; r++) filterJobs(jobs, "chennai");
8console.log("plain: 3 renders →", work, "computations");
9const memo = { deps: null, value: null };
10function useMemo(fn, deps) {
11 if (memo.deps && deps.every((d, i) => d === memo.deps[i])) return memo.value;
12 memo.deps = deps; memo.value = fn();
13 return memo.value;
14}
15work = 0;
16for (let r = 1; r <= 3; r++) useMemo(() => filterJobs(jobs, "chennai"), [jobs, "chennai"]);
17console.log("useMemo: 3 renders →", work, "computation");
18useMemo(() => filterJobs(jobs, "pune"), [jobs, "pune"]);
19console.log("city changed →", work, "computations (recomputed once)");
Your component filters 5,000 jobs by city. It re-renders because a COUNTER changed — and filters all 5,000 jobs again. And again. Same jobs, same city, same answer, paid for on every render.
Lesson 3 taught that re-renders are cheap — and they are, for building elements. But any heavy CALCULATION in the component body re-runs too. useMemo is the shelf for answers. A work counter will prove every claim.
📦 Memory boxes
what the program is remembering right now
nothing remembered yet
🖥️ What the computer shows
the answers the program prints out
nothing yet
1/10
UP NEXT IN REACT
Windowing — 10,000 rows, 12 DOM nodes
A node counter proves the whole technique: render only what the eye can see, and slide the window as the user scrolls.
useEffect timing — built from scratch, painted firstWindowing — 10,000 rows, 12 DOM nodes