Course contentsShow
← React
Lesson 894 of 2,39623. useMemo and useCallbackFree lesson

Alternative: Extract Expensive Logic Outside Component

Sometimes moving computation outside the component tree or to a Web Worker is better than memoizing inside render.

Alternative: Extract Expensive Logic Outside Component

What you'll learn: Sometimes the best optimization isn't useMemo—it's moving expensive calculations completely outside your component.

The Core Idea

Before reaching for useMemo, ask yourself: does this computation need to happen during render at all? If the expensive logic doesn't depend on props or state, you can often calculate it once outside the component tree entirely.

Think of it like meal prep: instead of chopping vegetables every time someone enters your kitchen (every render), you could chop everything once on Sunday afternoon and store it in containers. The kitchen visitors never see the chopping happen.

When to Extract Outside

This works beautifully when:

  • The computation depends only on static data or constants
  • You're processing imported data that never changes
  • The calculation can happen at module load time
  • Results can be stored in module-level variables

Simple Example Pattern

Instead of computing inside the component:

function ProductList() {
  // This runs on every render
  const sortedProducts = useMemo(() => {
    return STATIC_PRODUCTS.sort((a, b) => a.price - b.price);
  }, []);
  
  return <div>{/* render products */}</div>;
}

Extract it completely:

// Computed once when the module loads
const SORTED_PRODUCTS = STATIC_PRODUCTS.sort((a, b) => a.price - b.price);

function ProductList() {
  // Just use the pre-computed value
  return <div>{/* render SORTED_PRODUCTS */}</div>;
}

The second version is simpler, faster, and has zero render-time cost.

Why This Beats useMemo

No dependency array to maintain, no memoization overhead, no risk of stale closures—just a plain JavaScript constant that exists before React even starts rendering.

Key Takeaway: The fastest code is code that never runs during render—if computation doesn't need props or state, move it outside the component entirely.