When should you use useMemo()
What useMemo() returns
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:
useMemoreturns a value that is not recalculated unless it needs to be.
Example:
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)
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
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
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:
| Case | Why not |
|---|---|
The computation is light (for example, a + b) | The optimization costs more than the computation itself |
| Code written as "insurance" against re-renders | React is already optimized |
| You want to "speed up everything" | Premature optimization makes the code confusing |
An important rule
Use
useMemoonly if the computation is genuinely heavy or if it is passed as a prop to aReact.memocomponent.
Summary
| Question | Answer |
|---|---|
What does useMemo() return | The memoized (cached) value of the function |
| When it is recalculated | Only if the dependencies changed |
| When to use it | For heavy computations or to avoid unnecessary re-renders |
| When not to use it | For light expressions - it will only complicate the code |
| Alternative for functions | useCallback() (it caches the function itself, not a value) |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.