React Hooks
React useMemo Hook
useMemo caches the result of a calculation between renders and recomputes it only when one of its dependencies changes. It is a performance tool for expensive computations and for keeping object identities stable.
What is useMemo Hook in React?
useMemo caches the result of a calculation between renders and recomputes it only when one of its dependencies changes. It is a performance tool for expensive computations and for keeping object identities stable.
Why useMemo Hook matters
Sorting or filtering ten thousand rows on every keystroke makes a UI feel sluggish. Memoising the result means the work happens only when the inputs actually change.
useMemo Hook example
const visible = useMemo(() => {
return jobs
.filter(j => j.city === city)
.sort((a, b) => b.stipend - a.stipend);
}, [jobs, city]);How this works
The filter and sort run only when jobs or city changes. Typing in an unrelated search box re-renders the component but reuses the cached array.
Keeping an object identity stable
// Without useMemo this object is new every render, so the memoised
// child re-renders and any effect depending on it fires endlessly.
const config = useMemo(() => ({ city, role }), [city, role]);Key points to remember
- Memoise expensive computations, or values passed to memoised children and effect dependencies.
- useMemo is a hint — React may discard the cache to free memory.
- Do not memoise trivial arithmetic; the bookkeeping costs more than the work.
Common mistakes with useMemo Hook
- Wrapping everything in useMemo as a habit, which adds allocation and comparison cost.
- Passing an empty dependency array while the calculation reads changing values, producing stale results.
- Assuming useMemo prevents a re-render — it only avoids recomputation.
React useMemo Hook— Interview Questions & FAQs
What is the difference between useMemo and useCallback?+
useMemo caches a computed value; useCallback caches a function reference. useCallback(fn, deps) is exactly equivalent to useMemo(() => fn, deps).
Should I wrap every calculation in useMemo?+
No. Most calculations are far cheaper than the memoisation overhead. Profile first, then memoise the specific computation that shows up as slow.
