useMemo
In one line
useMemo is a Hook that caches (memoizes) a computed value, recomputing it only when its dependencies change.
In simple words
useMemo caches the result of a calculation. You pass a factory function and a dependency array: const value = useMemo(() => compute(a, b), [a, b]). React calls the factory on the first render and whenever a or b change; otherwise it returns the cached value.
Use useMemo for expensive calculations — sorting large arrays, complex transformations, deriving data from multiple sources. It prevents the calculation from running on every render when the inputs haven't changed.
useMemo is also used to preserve referential equality of objects/arrays passed as props to memoized child components. If you create a new array every render, React.memo on the child won't help — wrapping the array in useMemo keeps the same reference.
Example
const sortedItems = useMemo(() => {
return items.sort((a, b) => a.name.localeCompare(b.name));
}, [items]);
// Sort only runs when items changes, not on every render.The sort is expensive. useMemo caches the sorted array and only re-sorts when the items array reference changes.
Related terms
Related Resources
Related Lessons
- Memoization
Learn useMemo for caching computations.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.