How useMemo Works and Why is it Needed
useMemo is a React hook that allows memoizing a value, meaning saving calculation result between renders to avoid recalculating it without necessity.
It's especially useful if calculation is resource-intensive or depends on variables that rarely change.
Why useMemo?
React calls component again at each re-render, and all calculations are executed again, even if result will be the same. If function is heavy — it reduces performance.
Important:
useMemo doesn't guarantee cache — it can be cleared at low memory resource. This is optimization hint, not strict storage.
Syntax
const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);
computeExpensiveValue— function returning result.[a, b]— dependencies. If they haven't changed — React will return cached value.
Example: without useMemo
const App = ({ items }) => {
const filtered = items.filter(item => item.active); // every render — new filter
return <List data={filtered} />;
};
Every time on re-render filter will be called, even if items hasn't changed.
Example: with useMemo
const filtered = useMemo(() => {
return items.filter(item => item.active);
}, [items]);
Now filtering will occur only if items changes, otherwise cached value will be returned.
useMemo vs useCallback
| useCallback | useMemo | |
|---|---|---|
| What returns | Returns function | Returns value |
| Example | () => | heavyComputation() |
| Application | Used for handlers | Used for values |
When to Use useMemo
Good to use:
- For resource-intensive calculations (e.g.,
sort,filter,map,reduce) - When passing calculated values to
React.memo-components - When
valueis used as dependency inuseEffectoruseCallback