When working with React applications, every state update can trigger re-renders, and during those re-renders, expensive calculations might run again unnecessarily. This can slow down your app. React’s useMemo
hook helps optimize performance by memoizing values — caching the result of a computation so it’s only recalculated when needed.
What is useMemo
?
useMemo
is a React hook that returns a memoized value — meaning it remembers the result of a function and recomputes it only when its dependencies change.
Syntax:
const memoizedValue = useMemo(() => computeValue(), [dependencies]);
Why is it important?
- Avoids expensive recalculations on every render.
- Helps with performance optimization in CPU-intensive computations.
- Keeps reference stability for derived data (useful for passing data to child components without triggering unnecessary re-renders).
Example Without useMemo
import React, { useState } from 'react';
function App() {
const [count, setCount] = useState(0);
const [text, setText] = useState('');
const expensiveCalculation = (num) => {
console.log('Calculating...');
let total = 0;
for (let i = 0; i < 1000000000; i++) {
total += num;
}
return total;
};
const calculation = expensiveCalculation(count);
return (
<div>
<h1>Expensive Calculation: {calculation}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
);
}
Problem:
- Even when changing the
text
input (which has nothing to do withcount
),expensiveCalculation
runs again, wasting CPU cycles.
Example With useMemo
import React, { useState, useMemo } from 'react';
function App() {
const [count, setCount] = useState(0);
const [text, setText] = useState('');
const expensiveCalculation = (num) => {
console.log('Calculating...');
let total = 0;
for (let i = 0; i < 1000000000; i++) {
total += num;
}
return total;
};
const calculation = useMemo(() => expensiveCalculation(count), [count]);
return (
<div>
<h1>Expensive Calculation: {calculation}</h1>
<button onClick={() => setCount(count + 1)}>Increase</button>
<input value={text} onChange={(e) => setText(e.target.value)} />
</div>
);
}
What changes?
-
useMemo
stores the result ofexpensiveCalculation
. - It recalculates only when
count
changes, not whentext
changes. - This avoids unnecessary heavy computations and makes the UI more responsive.
When to Use useMemo
- When you have expensive calculations that don’t need to run on every render.
- When you want to avoid unnecessary recalculations for derived values.
- When passing computed data to
memo
ized child components.
When NOT to Use useMemo
- For simple or cheap calculations (memoization overhead can outweigh benefits).
- As a default — only use it when you detect a performance issue.
✅ Key takeaway:
useMemo
is all about optimizing expensive calculations by caching results between renders. It helps prevent wasteful re-computation and improves performance in complex React applications.
Top comments (0)