React · Lesson 55 of 120
useMemo
Skip slow work.
Every render runs your whole component again. Usually that's fast. But if a calculation is slow, you can ask React to remember its result, until its inputs change.
- Every render runs it all
- Some work is slow
- Remember the result
Filtering many orders
Filtering five thousand orders is slow work. Use memo remembers the result, and only runs the function again when min changes. Toggling the theme re-renders, but skips the filtering. We toggle the theme twice, then raise the minimum. Run it. Filtering ran only twice.
App.jsxjsx
import { useState, useMemo } from "react";
const ORDERS = Array.from({ length: 5000 }, (_, i) => ({ id: i, total: (i * 37) % 900 }));
export default function App() {
const [min, setMin] = useState(500);
const [dark, setDark] = useState(false);
const big = useMemo(() => {
console.log("filtering orders, min", min);
return ORDERS.filter(o => o.total >= min);
}, [min]);
return (
<div className="box" style={dark ? { background: "#222", color: "#fff" } : {}}>
<p>{big.length} orders of £{min} or more</p>
<button id="t" onClick={() => setDark(!dark)}>Toggle theme</button>
<button id="m" onClick={() => setMin(min + 100)}>Raise minimum</button>
</div>
);
}Output
filtering orders, min 500 filtering orders, min 600
Also uses style.css
body{font-family:-apple-system,Helvetica,Arial,sans-serif;margin:22px;font-size:21px;color:#1d1d1f;background:#fafafa}
h1{font-size:34px;margin:0 0 14px} h2{font-size:26px;margin:0 0 10px}
button{font-size:19px;padding:9px 18px;border-radius:9px;border:0;background:#61dafb;color:#111;font-weight:600;margin:4px 6px 4px 0}
input{font-size:19px;padding:8px 10px;border:2px solid #bbb;border-radius:8px}
li{margin:5px 0} .box{padding:14px;border-radius:12px;background:#fff;border:2px solid #ddd;margin:8px 0}
.done{text-decoration:line-through;color:#999} small{color:crimson;display:block;font-size:16px} .big{font-size:64px;font-weight:800}Also uses actions.json
[{"click": "#t", "times": 2}, {"click": "#m"}]When to memo
Measure first. Most calculations are fast enough without it. Use memo for genuinely slow work, or to keep an object the same between renders. And list every value it uses as a dependency.
| key | value |
|---|---|
| First | measure |
| Use for | slow calculations |
| Also | stable objects |
| Deps | everything it uses |
Summary
Use memo caches a slow calculation until its dependencies change. Next, use callback.
Key takeaways- useMemo(fn, [deps])
- Skip slow work
- Measure first
Next up: useCallback — stable functions