Course contentsShow
← React
Lesson 696 of 2,39618. When NOT to Use useEffectFree lesson

useMemo for Expensive Computations

When profiling confirms slowness, wrap expensive computation in useMemo with proper dependencies to skip re-computation on unchanged inputs.

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:

  1. Profiling confirms slowness (not gut feeling)
  2. The computation is genuinely expensive (complex loops, heavy processing)
  3. 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.