The useMemo hook caches (memoizes) the calculated result of an expensive computation between component renders, recalculating only when declared dependencies change.
flowchart TD
Render["Component Renders"] --> Check{"Dependencies Changed?"}
Check -- No --> Cached["Return Previously Computed Result (0ms)"]
Check -- Yes --> Recompute["Execute Calculation Function & Cache Result"]
import React, { useState, useMemo } from 'react';
// Synthetic dataset generator
const generateProducts = () => {
return Array.from({ length: 5000 }, (_, i) => ({
id: i + 1,
name: `Product ${i + 1}`,
price: Math.floor(Math.random() * 1000) + 1,
}));
};
const allProducts = generateProducts();
export default function FilteredProductList() {
const [maxPrice, setMaxPrice] = useState(500);
const [theme, setTheme] = useState('light');
// Expensive filtering computation memoized with useMemo
const filteredProducts = useMemo(() => {
console.log('Computing filtered products list...');
return allProducts.filter((product) => product.price <= maxPrice);
}, [maxPrice]); // Re-computes ONLY when maxPrice changes
return (
<div className={`container theme-${theme}`}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme (Current: {theme})
</button>
<div>
<label>Filter Max Price: ${maxPrice}</label>
<input
type="range"
min="10"
max="1000"
value={maxPrice}
onChange={(e) => setMaxPrice(Number(e.target.value))}
/>
</div>
<h3>Matching Products: {filteredProducts.length}</h3>
</div>
);
}
useMemouseEffect or memoized child components.useMemo(() => a + b, [a, b])) adds memory overhead without measurable speedup. Only memoize computationally expensive operations.useMemo should run during rendering and contain no side effects (API calls, DOM updates).Write a useMemo calculation that sorts a list of users alphabetically by name only when the users prop changes.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With