Have you heard about Hack Frontend Community?Join us on Telegram!
Practice React Problems

useMemo in React: Memoizing Expensive Computations

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

useCallbackuseMemo
What returnsReturns functionReturns value
Example() => heavyComputation()
ApplicationUsed for handlersUsed 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 value is used as dependency in useEffect or useCallback
Practice React Problems

By continuing to use the platform, you accept the terms of the Privacy Policy and the use of cookies.