useMemo for Heavy Array Operations
You'll learn how to prevent expensive array transformations from running on every render by memoizing their results.
The Problem with Array Methods
When you use methods like filter, map, reduce, or sort on large arrays inside your component, React runs them every single render—even when the underlying data hasn't changed. For a 10,000-item list that you're filtering and sorting, this can cause noticeable lag.
How useMemo Solves This
useMemo lets you cache the result of these operations. React will only recalculate when the dependencies (usually your source array or filter criteria) actually change:
const filteredAndSorted = useMemo(() => {
return items
.filter(item => item.price > minPrice)
.sort((a, b) => b.rating - a.rating);
}, [items, minPrice]);
Now the expensive filter + sort combo only runs when items or minPrice changes, not on every render caused by unrelated state updates.
Think of It Like Caching
Imagine manually alphabetizing 1,000 index cards every time someone asks "are these sorted?" even when no cards changed. Absurd, right? useMemo is you saying: "I already sorted these—here's the result—unless the cards themselves change."
When to Apply This
Profile first! Use this optimization when:
- Your array has hundreds or thousands of items
- Operations combine multiple methods (
filter().map().sort()) - You notice lag in DevTools Profiler
Don't memoize trivial operations on small arrays—the overhead isn't worth it.
Key Takeaway: Use useMemo to cache expensive array transformations like filtering, mapping, and sorting large datasets, preventing unnecessary recalculations on every render when the source data hasn't changed.