useMemo for Expensive Computations
You'll learn when and how to use useMemo to prevent costly re-calculations on every render.
The Problem
In the previous lesson, you saw expensive computations happening during render. Every time your component re-renders (due to state changes, parent updates, etc.), that expensive computation runs again—even when its inputs haven't changed. This can make your app feel sluggish.
The Solution: useMemo
useMemo is React's way of "remembering" the result of an expensive computation. It only re-calculates when specific dependencies change:
const expensiveResult = useMemo(() => {
// This only runs when 'data' changes
return data.map(item => /* complex processing */).filter(/* expensive check */);
}, [data]);
Think of it like a smart calculator with memory: if you ask it "what's 2 + 2?" multiple times in a row, it remembers the answer (4) instead of recalculating.
When to Use It
Only use useMemo when:
- Profiling confirms slowness (not gut feeling)
- The computation is genuinely expensive (complex loops, heavy processing)
- The dependencies don't change on every render
Example
function DataTable({ rawData, filters }) {
// Without useMemo: runs every render
// const processed = processLargeDataset(rawData, filters);
// With useMemo: only when rawData or filters change
const processed = useMemo(() => {
return processLargeDataset(rawData, filters);
}, [rawData, filters]);
return <Table data={processed} />;
}
Key Takeaway: Use useMemo to wrap expensive computations with proper dependencies, but only after profiling proves it's necessary—premature optimization adds complexity without benefit.