Loading lessons...
Memoizing Values with useMemo
Memoizing Values with useMemo
When a component performs computationally expensive calculations (like sorting large datasets, filtering thousands of array items, or performing complex math operations), running those calculations on every render can cause UI lag.
What is useMemo?
The useMemo hook caches (memoizes) the result of a calculation between component re-renders.
import { useState, useMemo } from 'react';
function ProductCatalog({ products, selectedCategory }) {
const [searchTerm, setSearchTerm] = useState('');
// Expensive filtering calculation memoized with useMemo
const filteredProducts = useMemo(() => {
console.log("Filtering products..."); // Runs only when products or selectedCategory change
return products.filter(p => p.category === selectedCategory);
}, [products, selectedCategory]); // Dependency array
return (
<div>
<input
value={searchTerm}
onChange={e => setSearchTerm(e.target.value)}
placeholder="Search..."
/>
<ul>
{filteredProducts.map(p => <li key={p.id}>{p.name}</li>)}
</ul>
</div>
);
}
In the example above, typing into the searchTerm input re-renders the component, but filteredProducts is NOT re-calculated because products and selectedCategory dependencies have not changed!
When to Use useMemo
- Expensive Calculations: Filtering, sorting, or transforming large data structures ($O(n^2)$ operations).
- Preserving Reference Equality: Caching an object/array passed as a prop to a
React.memochild component.
// Preserving object reference for React.memo child
const config = useMemo(() => ({ theme: 'dark', lang: 'en' }), []);
return <MemoizedChild config={config} />;
Do NOT wrap every single calculation in useMemo. Overusing useMemo adds memory overhead and dependency tracking costs that can outweigh performance gains for simple operations.
Summary & TL;DR
useMemo(() => calculate(), [deps])caches the result of a calculation.- Re-calculates value only when dependency variables change.
- Useful for expensive algorithms and maintaining object reference equality for child props.