React / 51
useMemo and useCallback
useMemo caches a calculated value between renders; useCallback caches a function. Use them for slow calculations and stable props, not everywhere.
Same value vs same object
5 === 5numbers compare by value
"veg" === "veg"so do strings and booleans
{} === {}two different objects
[] === []two different arrays
(() => {}) === (() => {})two different functions
useMemo / useCallback resultsame object until a dependency changes
This is the whole reason these hooks exist. React compares props and dependencies with Object.is. Numbers and strings compare by value; objects, arrays and functions compare by identity: "is this the very same thing in memory?". A new {} each render is never the same thing.
useMemo: cache a calculation
import { useMemo, useState } from "react";
export default function Menu({ items }) {
const [query, setQuery] = useState("");
const [cart, setCart] = useState([]);
const visible = useMemo(
() => items.filter((i) => i.name.toLowerCase().includes(query.toLowerCase())),
[items, query]
);
// …
}On the first render, React runs the function and stores the result. On later renders, if items and query are the same as last time, it hands back the stored array without filtering again. Adding to the cart re-renders Menu, but visible is reused.
useCallback: cache a function
useCallback(fn, deps) gives you the same function on every render until a dependency changes. It's shorthand for useMemo(() => fn, deps). Here's the whole menu, with both hooks feeding a memo child:
import { memo, useCallback, useMemo, useState } from "react";
const MenuList = memo(function MenuList({ items, onAdd }) {
return items.map((i) => <button key={i.id} onClick={() => onAdd(i)}>{i.name}</button>);
});
export default function Menu({ items }) {
const [query, setQuery] = useState("");
const [cart, setCart] = useState([]);
const visible = useMemo(
() => items.filter((i) => i.name.toLowerCase().includes(query.toLowerCase())),
[items, query]
);
const handleAdd = useCallback((item) => setCart((c) => [...c, item]), []);
return (
<>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<p>{cart.length} in cart</p>
<MenuList items={visible} onAdd={handleAdd} />
</>
);
}Click a dish: cart changes and Menu re-renders. But visible is the same array (items and query didn't change) and handleAdd is the same function (its dependency list is empty, and a state setter never changes). So MenuList gets identical props and skips its render. Remove either hook and it re-renders on every click.
When they help, and when they don't
| Helps | Doesn't help |
|---|---|
| A calculation that's measurably slow (React's docs suggest timing it: around 1 ms or more is worth a look) | Cheap work: a + b, a short .map(), formatting a string |
A value or function passed to a memo child | Props passed to a child that isn't wrapped in memo (it re-renders anyway) |
A value or function used as a useEffect dependency, so the effect doesn't re-run every render | Everywhere "just in case": it adds code, and the cache itself has a cost |
Don't
Memoize everything
const total = useMemo(() => price * qty, [price, qty]);
const label = useMemo(() => `${qty} items`, [qty]);
const onClick = useCallback(() => setOpen(true), []);
// passed to a plain <button>: no benefitDo
Memoize what you measured
const total = price * qty;
const label = `${qty} items`;
const visible = useMemo(
() => filterAndSort(items, query), // slow: 5,000 items
[items, query]
);Gotchas
Recall
Can you answer these?
0/4
Answer out loud (or in your head) before you tap. That's what makes it stick.
Saved on this device only. No login.
