How to Use useMemo in React
As the creator of CoreUI and with over 11 years of React development experience, I’ll show you how to effectively use the useMemo hook for performance optimization.
The useMemo hook memoizes expensive calculations and only recalculates when dependencies change, preventing unnecessary re-renders and improving performance.
import React, { useMemo, useState } from 'react'
function ExpensiveComponent({ items, filter }) {
const [count, setCount] = useState(0)
// Expensive calculation that should only run when items or filter change
const filteredItems = useMemo(() => {
console.log('Filtering items...')
return items.filter(item =>
item.name.toLowerCase().includes(filter.toLowerCase())
).sort((a, b) => a.name.localeCompare(b.name))
}, [items, filter])
// This calculation runs on every render without useMemo
const itemCount = useMemo(() => {
return filteredItems.length
}, [filteredItems])
return (
<div>
<p>Found {itemCount} items</p>
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
{filteredItems.map(item => (
<div key={item.id}>{item.name}</div>
))}
</div>
)
}
The useMemo hook takes two arguments: a function that returns the computed value and a dependency array. The computation only runs when dependencies in the array change. Use useMemo for expensive calculations, complex object transformations, or when passing computed values to child components that are wrapped in React.memo. Avoid overusing useMemo for simple calculations as the memoization overhead might outweigh the benefits.
Best Practice Note:
In CoreUI components, we strategically use useMemo for filtering large datasets, computing component themes, and processing configuration objects. This ensures our UI components remain performant even with complex data transformations and frequent re-renders.



