🪝 Introduction to useMemo
The useMemo Hook is a React Hook that lets you memoize the result of an expensive calculation. Instead of recalculating a value on every render, React stores the previously computed value and recalculates it only when one of its dependencies changes. This helps improve performance in components that perform costly computations.
Important
🎯 Why Use useMemo?
Every time a component re-renders, JavaScript expressions inside the component are executed again. If a calculation is expensive, repeatedly performing it can slow down the application. useMemo prevents unnecessary recalculations by remembering the previous result until its dependencies change.
- Avoid repeated expensive calculations.
- Improve rendering performance.
- Memoize derived values.
- Reduce unnecessary work during re-renders.
⚙️ Syntax
Basic Syntax
const memoizedValue = useMemo(() => {
return expensiveCalculation();
}, [dependencies]);| Part | Description |
|---|---|
| useMemo() | Memoizes a calculated value. |
| Callback Function | Returns the value to be cached. |
| Dependency Array | Determines when the value should be recalculated. |
🔄 How useMemo Works
💻 Example 1: Expensive Calculation
Using useMemo
import { useMemo } from "react";
function Numbers({ numbers }) {
const total = useMemo(() => {
return numbers.reduce((sum, number) => sum + number, 0);
}, [numbers]);
return <h2>{total}</h2>;
}The total is calculated only when the numbers array changes. Otherwise, React reuses the previously calculated value.
💻 Example 2: Filtering Data
Filtering a List
import { useMemo } from "react";
function ProductList({ products, search }) {
const filteredProducts = useMemo(() => {
return products.filter(product =>
product.name.includes(search)
);
}, [products, search]);
return (
<ul>
{filteredProducts.map(product => (
<li key={product.id}>
{product.name}
</li>
))}
</ul>
);
}Filtering occurs only when either the product list or the search text changes.
💻 Example 3: Sorting Data
Sorting Items
import { useMemo } from "react";
function Scores({ scores }) {
const sortedScores = useMemo(() => {
return [...scores].sort((a, b) => b - a);
}, [scores]);
return (
<ul>
{sortedScores.map(score => (
<li key={score}>{score}</li>
))}
</ul>
);
}Sorting large datasets repeatedly can be expensive. useMemo ensures sorting happens only when the input array changes.
📊 Without vs With useMemo
| Without useMemo | With useMemo |
|---|---|
| Calculation runs on every render. | Calculation runs only when dependencies change. |
| May reduce performance. | Can improve performance for expensive computations. |
| No cached result. | Previously calculated value is reused. |
📋 Common Use Cases
Memoize expensive mathematical or business calculations.
Cache filtered collections instead of filtering during every render.
Prevent repeated sorting of large arrays.
Compute derived values from existing props or state efficiently.
📅 Memoization Process
React renders the component.
React checks the dependency array.
If dependencies changed, the calculation runs again.
The calculated value is cached for future renders.
If dependencies remain unchanged, React returns the cached value.
⚠️ Common Mistakes
- Using useMemo for inexpensive calculations.
- Providing an incorrect dependency array.
- Expecting useMemo to prevent component re-renders.
- Using memoization everywhere without measuring performance.
Warning
📊 useMemo vs useCallback
| Feature | useMemo | useCallback |
|---|---|---|
| Returns | A memoized value. | A memoized function. |
| Primary Purpose | Cache expensive calculations. | Cache function references. |
| Common Usage | Filtering, sorting, derived data. | Passing callbacks to child components. |
✅ Best Practices
- Use useMemo only for expensive calculations.
- Keep dependency arrays accurate and complete.
- Measure performance before adding memoization.
- Memoize derived data instead of recalculating it repeatedly.
- Remember that readability is often more important than unnecessary optimization.
📚 Official Resource
Learn more about useMemo in the official React documentation at React useMemo Documentation.