Skip to main content
Practice Problems

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

jsx
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

jsx
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

jsx
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

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems