The Analogy: A Tool-and-Die Shop's Numbered Fixture Rack
Grinding a precision fixture -- a steel jig that holds a part at exact angles for machining -- is slow and costly work. A well-run tool-and-die shop grinds each fixture once, hangs it on a numbered rack, and clips a spec tag to it listing the dimensions it was ground for. When the next job order arrives, the foreman reads the order's spec, compares it to the tag, and if they match he simply lifts the finished fixture off the rack. The expensive grind is skipped entirely; the shelved fixture is the cached result.
The rack only re-grinds when the inputs genuinely change. If a new order lists the same dimensions as the tag, the old fixture is reused as-is. If the order lists different dimensions, the tag no longer matches, so the old fixture is retired and a fresh one is ground and re-hung with an updated tag. The spec tag is the whole decision: same spec, same fixture; changed spec, new fixture. Nothing about how many orders pass through matters -- only whether the tagged inputs moved.
Downstream, an assembly station clamps its work to whatever fixture it is handed and calibrates its stops to that exact physical fixture. As long as it keeps receiving the very same fixture, it trusts its existing calibration and does no setup at all. Hand it a different fixture -- even one ground to identical dimensions -- and it must tear down and recalibrate from scratch, because it recognises the physical object, not the numbers on the tag. So handing downstream a stable fixture is precisely what lets that station skip its setup, and grinding a fresh identical fixture every order forces a needless recalibration each time.
The rack is not free, and that is where shops get it wrong. Every fixture hung on it consumes a slot, a printed tag, and a foreman's glance to check the tag before each job. For a cut so quick that simply redoing it beats walking to the rack and reading the tag, the rack is pure overhead -- clutter that slows the floor instead of speeding it. Worse, if someone changes the spec but forgets to update the tag, the foreman keeps pulling a stale fixture and every part comes out to the old, wrong dimensions until an inspector catches it. Caching pays only when the saved grinding outweighs the bookkeeping, and only when the tag faithfully lists everything the fixture depends on.
Syntax or Core Structure
useMemo caches a computed value and useCallback caches a function's identity; both take a dependency array and only rebuild when a dependency changes. React.memo wraps a component so it skips re-rendering when its props are unchanged.
import { useMemo, useCallback, memo } from "react";
function List({ items, query }) {
// Recompute the filtered list only when items or query change.
const visible = useMemo(
() => items.filter((it) => it.includes(query)),
[items, query]
);
// Keep the same onSelect identity across renders.
const onSelect = useCallback((id) => console.log("picked", id), []);
return visible.map((it) => <Row key={it} label={it} onSelect={onSelect} />);
}
// Row re-renders only when its props change by identity.
const Row = memo(function Row({ label, onSelect }) {
return <button onClick={() => onSelect(label)}>{label}</button>;
});
That renders in a browser, so it has no console output. The behaviour that matters -- "recompute only when a dependency's identity changes" -- is a pure decision we can model and run. A memo cell caches its last dependencies and value, and recomputes only when the new deps differ by Object.is:
function sameDeps(a, b) {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (!Object.is(a[i], b[i])) return false;
}
return true;
}
function makeMemoCell() {
let cachedDeps = null;
let cachedValue = null;
let computeCount = 0;
return function memo(compute, deps) {
if (cachedDeps === null || !sameDeps(cachedDeps, deps)) {
cachedValue = compute();
cachedDeps = deps;
computeCount++;
}
return { value: cachedValue, computeCount: computeCount };
};
}
const useMemoCell = makeMemoCell();
console.log(useMemoCell(function () { return "sum(1,2)=3"; }, [1, 2]));
console.log(useMemoCell(function () { return "sum(1,2)=3"; }, [1, 2]));
console.log(useMemoCell(function () { return "sum(1,5)=6"; }, [1, 5]));
Output:
{ value: 'sum(1,2)=3', computeCount: 1 }
{ value: 'sum(1,2)=3', computeCount: 1 }
{ value: 'sum(1,5)=6', computeCount: 2 }
The first call has no cache, so it computes and computeCount becomes 1. The second call passes [1, 2] again; sameDeps is true, so the cached value is returned and the count stays 1 -- the grind was skipped. The third call passes [1, 5]; the second element changed, sameDeps is false, so it recomputes and the count rises to 2. That is the whole of useMemo: a spec tag checked before every grind.
Technical Depth: Identity, Skipping, and the Cost of the Rack
useCallback is useMemo for a function
useCallback(fn, deps) is defined as useMemo(() => fn, deps): instead of caching a computed value, it caches the function itself, so the same function identity survives across renders until a dependency changes. That stable identity is what a downstream React.memo child needs to skip its work.
const useCb = makeMemoCell();
const f1 = useCb(function () { return function handleClick() {}; }, ["a"]).value;
const f2 = useCb(function () { return function handleClick() {}; }, ["a"]).value;
const f3 = useCb(function () { return function handleClick() {}; }, ["b"]).value;
console.log("stable while deps same:", Object.is(f1, f2));
console.log("new when deps change: ", Object.is(f1, f3));
Output:
stable while deps same: true
new when deps change: false
With deps ["a"] unchanged, the cell returns the exact same function object, so Object.is(f1, f2) is true -- the same fixture off the rack. Changing deps to ["b"] forces a new function, so Object.is(f1, f3) is false. The cook downstream can tell the difference.
React.memo skips a child when props are unchanged
React.memo compares each incoming prop to the previous render's with Object.is -- a shallow check -- and renders only if one differs. The table shows a memoized child receiving an onClick prop across three parent renders:
| Parent render | onClick passed | Object.is vs previous | memo child |
|---|---|---|---|
| 1 | A | (no previous) | render |
| 2 | A (stable) | true | skip |
| 3 | B (new) | false | render |
function memoChild(props, prevProps) {
const same = prevProps !== null && Object.is(props.onClick, prevProps.onClick);
return same ? "skip" : "render";
}
const A = function () {};
const B = function () {};
console.log(memoChild({ onClick: A }, null));
console.log(memoChild({ onClick: A }, { onClick: A }));
console.log(memoChild({ onClick: B }, { onClick: A }));
Output:
render
skip
render
The first render has no previous props and must render. The second receives the same A, so Object.is is true and the child skips. The third receives a new B, so it renders again. This is why an unstable callback silently defeats React.memo: a fresh function every render always looks like B.
Memoizing costs something too
The cache only helps when it hits. If a dependency is a brand-new object every render, sameDeps is always false and the grind runs every time -- you pay the comparison and gain nothing:
const cell = makeMemoCell();
let r = null;
for (let i = 1; i <= 3; i++) {
const unstableDep = { i: 1 }; // new identity every render, same content
r = cell(function () { return "computed"; }, [unstableDep]);
}
console.log("computeCount after 3 renders:", r.computeCount);
Output:
computeCount after 3 renders: 3
Each iteration builds a fresh unstableDep, so Object.is against the cached dep is always false and the count climbs to 3 -- zero cache hits. Memoizing a value whose dependencies are themselves unstable is worse than not memoizing, because you carry the bookkeeping and still recompute. Stabilise the inputs first, or do not memoize at all.
Real World Example: A Filtered Product List That Re-Renders Every Row
A search screen holds a query in state and derives a filtered list from a large product array, rendering each result as a React.memoed Row that receives an onSelect callback. The list should re-filter only when the query or the products change, and each row should re-render only when its own data changes. A naive version re-filters on every render and re-renders every row on every render; a careful version does neither. The model below counts both, reusing the makeMemoCell from earlier.
function runList(renders, memoizeFilter, stableCallback) {
const products = ["Ada", "Ben", "Cid"]; // stable array identity
const query = ""; // unchanged across these renders
const filterCell = makeMemoCell();
let firstCb = null;
let filterRuns = 0;
let rowRenders = 0;
for (let i = 1; i <= renders; i++) {
if (memoizeFilter) {
filterRuns = filterCell(function () {
return products.filter(function (p) { return p.indexOf(query) >= 0; });
}, [products, query]).computeCount;
} else {
filterRuns++; // recompute every render
}
const onSelect = stableCallback ? (firstCb || function () {}) : function () {};
if (i === 1) firstCb = onSelect;
const rowSkips = i > 1 && stableCallback && Object.is(onSelect, firstCb);
if (!rowSkips) rowRenders++;
}
return "filterRuns=" + filterRuns + " rowRenders=" + rowRenders;
}
console.log("naive: ", runList(3, false, false));
console.log("memoized: ", runList(3, true, true));
Output:
naive: filterRuns=3 rowRenders=3
memoized: filterRuns=1 rowRenders=1
In the naive run the filter recomputes on all three renders and, because onSelect is a fresh function each time, every row re-renders too: filterRuns=3 rowRenders=3. In the memoized run the filter's deps (products, query) never change identity, so it computes once and the count stays at 1; onSelect is the same function after the first render, so the memoized rows skip renders 2 and 3, leaving rowRenders=1. Same visible list, a third of the work.
The gap widens with list size and render frequency: a parent that re-renders on an unrelated state change -- a theme toggle, a clock tick -- pays the full filter-and-render bill every time in the naive version, and nothing in the memoized one. This is the case memoization is actually for: a genuinely expensive derivation and a long list of memoized children, not a two-item list computed in a microsecond.
The design flaw is hidden in how the model treats onSelect as trivially stable. A real row handler must know which row was clicked, and the tempting fix is onClick={() => onSelect(row.id)} in the parent -- but that allocates a new function per row on every render, so Object.is is always false and React.memo never skips, exactly the naive case. The real fix is a single stable onSelect created once with useCallback(fn, []) that receives the id as an argument at call time, so every row gets the same function identity. And a caution the model cannot show: useMemo and useCallback are hints, not guarantees -- React may discard a cached value and recompute -- so correctness must never depend on a cache hit, only performance.
Common Mistakes
- Memoizing everything. Wrapping trivially cheap computations in
useMemoadds a dependency comparison and extra memory for no benefit; for a fast calculation, just re-running it beats checking the rack.
- Passing an unstable dependency. A fresh object, array, or function in the deps array makes
Object.isalways report a change, so the cache never hits and you pay the overhead with none of the savings.
- Omitting a dependency the computation reads. Leaving a value out of the deps array yields a stale cached result -- the fixture ground to last week's spec. The exhaustive-deps lint rule flags this.
- Stabilising one prop but not the others. A
useCallbacked handler passed alongside a fresh inlinestyle={{...}}object still re-renders theReact.memochild, because one changed prop is enough.
- Using useMemo for side effects.
useMemocomputes a value during render and must stay pure; network calls, subscriptions, and logging belong inuseEffect.
- Expecting React.memo to deep-compare props. By default it does a shallow
Object.ischeck; a prop object with the same contents but a new identity counts as changed.
- Binding per-item data into a callback. Writing
onClick={() => onSelect(id)}in the parent creates a new function per row every render, defeatingReact.memoon the rows.
- Relying on the cache for correctness. React may drop a memoized value and recompute at will;
useMemo/useCallbackare performance hints, so code must be correct even if they recompute every render.
- Memoizing before measuring. Adding
useMemo/useCallbackblindly can make code slower and harder to read; without profiling you often optimise a path that was never hot.
Best Practices
- Measure first with the React Profiler, then memoize the specific hot path you found rather than sprinkling memoization everywhere.
- Keep dependency arrays complete and honest, and let the exhaustive-deps lint rule guide you toward the values the computation actually uses.
- Stabilise the inputs -- objects, arrays, and callbacks -- so that downstream
useMemoandReact.memocan actually hit their caches.
- Use
useCallbackfor functions you hand toReact.memochildren or list in another hook's dependency array.
- Prefer one stable handler that takes an id argument over a separate callback bound per list item.
- Treat
useMemoanduseCallbackas hints, never guarantees; never let correctness depend on a cached value surviving.
- Reach for cheaper structural fixes first -- lifting static content out, splitting a component, or moving state down -- before adding memoization.
- Pair
React.memoon a child with stable props from the parent; either one alone buys nothing.
Practice Exercises
- Trace the
makeMemoCellmodel for the calls[1, 2],[1, 2], then[1, 5]. Give the value andcomputeCountreturned by each and state which call was served from the cache.
- Run the unstable-dependency loop on paper and explain why
computeCountreaches 3 across three renders. What single change tounstableDepwould make it 1?
- Run
runList(3, false, false)andrunList(3, true, true)by hand, and explain each of thefilterRunsandrowRendersfigures in terms of dependency identity and callback identity.
- A memoized
Rowstill re-renders every keystroke because the parent passesonClick={() => select(row.id)}. Explain why, and rewrite the parent and row soReact.memocan skip unchanged rows.