How to use useMemo in React
Using useMemo is essential for optimizing React applications by memoizing expensive calculations and preventing unnecessary re-computations during renders. As the creator of CoreUI, a widely used open-source UI library, I’ve implemented useMemo in numerous React components for data processing, filtering operations, and complex calculations in performance-critical enterprise applications. From my expertise, the most effective approach is to use useMemo for expensive computations with proper dependency arrays. This method provides significant performance improvements while maintaining code readability and preventing optimization-related bugs through careful dependency management.
Use useMemo
hook to memoize expensive calculations and prevent unnecessary re-computations.
import { useMemo, useState } from 'react'
function ProductList({ products, searchTerm, sortBy }) {
const [showOnlyInStock, setShowOnlyInStock] = useState(false)
// Memoize filtered and sorted products
const processedProducts = useMemo(() => {
console.log('Processing products...') // This will only run when dependencies change
let filtered = products.filter(product =>
product.name.toLowerCase().includes(searchTerm.toLowerCase())
)
if (showOnlyInStock) {
filtered = filtered.filter(product => product.inStock)
}
return filtered.sort((a, b) => {
if (sortBy === 'name') return a.name.localeCompare(b.name)
if (sortBy === 'price') return a.price - b.price
return 0
})
}, [products, searchTerm, showOnlyInStock, sortBy])
// Memoize expensive calculation
const totalValue = useMemo(() => {
return processedProducts.reduce((sum, product) => sum + (product.price * product.quantity), 0)
}, [processedProducts])
return (
<div>
<label>
<input
type="checkbox"
checked={showOnlyInStock}
onChange={(e) => setShowOnlyInStock(e.target.checked)}
/>
Show only in stock
</label>
<p>Total Value: ${totalValue.toFixed(2)}</p>
<p>Showing {processedProducts.length} products</p>
{processedProducts.map(product => (
<div key={product.id}>
<h3>{product.name}</h3>
<p>Price: ${product.price}</p>
<p>Stock: {product.inStock ? 'In Stock' : 'Out of Stock'}</p>
</div>
))}
</div>
)
}
The useMemo
hook memoizes the result of expensive calculations and only re-computes when dependencies in the dependency array change. This prevents unnecessary work during re-renders when unrelated state changes. Use useMemo for complex data transformations, filtering/sorting operations, and expensive calculations. The dependency array works like useEffect - include all variables from component scope that the calculation uses. Only use useMemo when you have actual performance issues, as premature optimization can make code harder to read.
Best Practice Note:
This is the same approach we use in CoreUI React components for optimizing data-heavy interfaces and dashboard performance. Profile your app first to identify actual performance bottlenecks, use React DevTools Profiler to measure impact, and remember that useMemo has overhead - only use it for genuinely expensive operations or when preventing child component re-renders.