Loading...
Loading...
By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.
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.
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.
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.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.
const filtered = useMemo(() => {
return items.filter(item => item.active);
}, [items]);
Now filtering will occur only if items changes, otherwise cached value will be returned.
| useCallback | useMemo | |
|---|---|---|
| What returns | Returns function | Returns value |
| Example | () => | heavyComputation() |
| Application | Used for handlers | Used for values |
Good to use:
sort, filter, map, reduce)React.memo-componentsvalue is used as dependency in useEffect or useCallback