React Hooks Series
useMemo
Cache the result of an expensive calculation. useMemo only recomputes when its dependencies change, every other render returns the cached value instantly.
01 — What it is
01
The signatureconst value = useMemo(() => {
return expensiveCalculation(data);
}, [data]); // recompute only when 'data' changesuseMemo returns a value. Compare with useCallback which returns a function. Don't overuse it — only memoize genuinely expensive operations.02
When to use it| Good use case | Bad use case |
|---|---|
| Filtering/sorting large arrays | Simple arithmetic |
| Expensive derived calculations | String concatenation |
| Stable object reference for child props | Values that change every render anyway |
02 — Live demo
↓
MemoTutorial — interactiveThe app fetches 500 comments and finds the longest name. Click Toggle to re-render — the compute count doesn't increase because data hasn't changed.
Fetching comments…
Computed 1 time(s)
Next: useCallback — memoize functions so child components don't re-render unnecessarily.