Part 18: useMemo Hook: Caching Expensive Computations
Performance optimization in React involves avoiding unnecessary recalculations and re-renders. The useMemo hook memoizes (caches) the result of an expensive calculation between renders.
1. Syntax and Working Mechanism
const cachedValue = useMemo(() => calculateValue(a, b), [a, b]);
- On initial render, React runs the function and saves the result.
- On subsequent renders, React checks if the dependencies (
[a, b]) changed. - If unchanged, it returns the previously cached value without recalculating.
2. Real-World Example: Filtering a Large Dataset
import { useState, useMemo } from 'react';
export default function UserDirectory({ users }) {
const [search, setSearch] = useState('');
const [selectedRole, setSelectedRole] = useState('All');
// Expensive filtering calculation memoized
const filteredUsers = useMemo(() => {
console.log('Filtering users list...');
return users.filter(user => {
const matchesSearch = user.name.toLowerCase().includes(search.toLowerCase());
const matchesRole = selectedRole === 'All' || user.role === selectedRole;
return matchesSearch && matchesRole;
});
}, [users, search, selectedRole]);
return (
<div>
<input
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder="Filter by name..."
/>
<ul>
{filteredUsers.map(user => (
<li key={user.id}>{user.name} - {user.role}</li>
))}
</ul>
</div>
);
}
3. When NOT to Use useMemo
Do not wrap every single calculation in useMemo. useMemo itself has overhead (allocating memory for closures and comparing dependency arrays). Only use it when:
1. The calculation is noticeably slow (e.g., thousands of items, complex regex).
2. You pass the resulting object/array to a child component optimized with React.memo.
Key Takeaways
useMemocaches the calculated return value of a function.- It only recalculates when one of its specified dependencies changes.
- Avoid premature optimization on trivial operations.
In Part 19, we explore useCallback for function reference memoization!

