When Computation is Expensive: useMemo
What you'll learn: How to use useMemo to cache expensive calculations so they don't re-run on every render, avoiding the mistake of using useEffect for this.
The Problem: Expensive Calculations
In the previous lesson, you learned to compute derived values during render instead of in a useEffect. But what if that calculation is genuinely expensive—like filtering thousands of items, running complex algorithms, or processing large datasets?
function ProductList({ products, searchTerm }) {
// This runs on EVERY render, even if products/searchTerm didn't change!
const filtered = products
.filter(p => p.name.includes(searchTerm))
.sort((a, b) => b.rating - a.rating);
return <div>{filtered.map(p => <Product key={p.id} {...p} />)}</div>;
}
If products has 10,000 items and the parent re-renders for an unrelated reason (like hover state changing), this expensive filtering happens again unnecessarily.
The Solution: useMemo
useMemo caches the result of a calculation and only re-computes when specific dependencies change:
function ProductList({ products, searchTerm }) {
const filtered = useMemo(() => {
return products
.filter(p => p.name.includes(searchTerm))
.sort((a, b) => b.rating - a.rating);
}, [products, searchTerm]); // Only re-run if these change
return <div>{filtered.map(p => <Product key={p.id} {...p} />)}</div>;
}
Now the expensive work only happens when products or searchTerm actually changes—not on every render.
When to Use It
- Don't optimize prematurely. Most calculations are fast enough.
- Use
useMemowhen you measure a performance problem. - Common cases: filtering large lists, complex math, generating heavy data structures.
Key Takeaway: Use useMemo to cache expensive derived values based on dependencies—keeping computation during render, but avoiding unnecessary work. Never reach for useEffect + useState for this pattern.