Skip to main content

When should you use useMemo()

What useMemo() returns

javascript
const memoizedValue = useMemo(() => computeSomething(a, b), [a, b]);

useMemo() returns the result of the function you passed in. React remembers (caches) that result and returns it again if the dependencies [a, b] have not changed.

In simple terms: useMemo returns a value that is not recalculated unless it needs to be.

Example:

javascript
const doubled = useMemo(() => count * 2, [count]);

If count does not change -> useMemo returns the old value of doubled, and the function () => count * 2 does not run again.


When you should use useMemo()

useMemo is a performance optimization tool, so it should be used deliberately, and only where it is justified.


Use useMemo when:

1. There are heavy computations

(sorting, filtering, long loops, large computations)

javascript
const sortedUsers = useMemo(() => { console.log("Sorting..."); return [...users].sort((a, b) => a.name.localeCompare(b.name)); }, [users]);

Without useMemo, the sorting would run on every render, even if users did not change.


2. You want to avoid unnecessary re-renders of child components

javascript
const filtered = useMemo( () => users.filter(u => u.active), [users] ); return <UserList users={filtered} />;

If UserList is wrapped in React.memo, it will not re-render until filtered changes. Without useMemo a new array would be created on every render, and UserList would think the users prop had changed.


3. You need to memoize derived data

javascript
const totalPrice = useMemo( () => cart.reduce((sum, item) => sum + item.price, 0), [cart] );

The total is recalculated only when cart changes.


4. You use complex computations inside useEffect or useCallback

Sometimes useMemo helps stabilize dependencies so the effect is not called unnecessarily.


You should not use useMemo when:

CaseWhy not
The computation is light (for example, a + b)The optimization costs more than the computation itself
Code written as "insurance" against re-rendersReact is already optimized
You want to "speed up everything"Premature optimization makes the code confusing

An important rule

Use useMemo only if the computation is genuinely heavy or if it is passed as a prop to a React.memo component.


Summary

QuestionAnswer
What does useMemo() returnThe memoized (cached) value of the function
When it is recalculatedOnly if the dependencies changed
When to use itFor heavy computations or to avoid unnecessary re-renders
When not to use itFor light expressions - it will only complicate the code
Alternative for functionsuseCallback() (it caches the function itself, not a value)

Short Answer

Interview ready
Premium

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