useMemo caches the result of a calculation between renders. It is mainly a performance optimization for expensive calculations.
1 Memoization
Memoization means remembering a calculation result and reusing it while its dependencies remain unchanged.
flowchart TD
A[Render] --> B[Check Dependencies]
B --> C{Changed}
C -->|No| D[Reuse Cached Result]
C -->|Yes| E[Calculate Again]
E --> F[Store Result]
D --> G[Use Value]
F --> G
2 Basic Example
const filteredProducts = useMemo(
() => products.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
),
[products, search]
);
3 Important Point
useMemo does not prevent the component from rendering. It caches the calculation result.
4 Object Identity
const options = useMemo(
() => ({ sort: "price" }),
[]
);
This can provide a stable object reference when that identity matters to another optimization.
5 useMemo vs useCallback vs React.memo
| Tool | Purpose |
|---|---|
| useMemo | Memoizes a calculated value |
| useCallback | Memoizes a function reference |
| React.memo | Can skip child rendering when props are unchanged |
6 Complete Example
function ProductDashboard({ products, search }) {
const filtered = useMemo(
() => products.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
),
[products, search]
);
const total = useMemo(
() => filtered.reduce(
(sum, product) => sum + product.price,
0
),
[filtered]
);
return (
<section>
{filtered.map(product => (
<p key={product.id}>{product.name}</p>
))}
<strong>Total: ₹{total}</strong>
</section>
);
}
7 When Not to Use It
- Simple calculations.
- No meaningful performance issue.
- When it only makes code harder to understand.
8 Common Mistakes
- Using useMemo everywhere.
- Missing dependencies.
- Thinking it prevents component rendering.
- Confusing it with useCallback.
9 Interview Questions
- What is useMemo?
- What is memoization?
- When should useMemo be used?
- Does useMemo prevent rendering?
- What is the difference between useMemo and useCallback?
10 Key Takeaways
- useMemo caches a value.
- The calculation runs again when dependencies change.
- It is a performance optimization.
- Do not use it blindly.
Conclusion
Use useMemo when caching a calculation provides a real benefit. Understanding dependencies and measuring performance are more important than adding memoization everywhere.