Course contentsShow
← React
Lesson 393 of 2,39611. useState Patterns and PitfallsFree lesson

Lazy Init vs useMemo: Different Tools

Understand that lazy initialization is for first-render cost, while useMemo optimizes re-render cost—don't confuse them.

Lazy Init vs useMemo: Different Tools

What you'll learn: How lazy initialization and useMemo solve different performance problems—and why using one doesn't replace the other.

Two Different Performance Tools

Now that you've seen lazy initialization with useState(() => value), you might wonder: "Isn't this just like useMemo?" The short answer: no, they solve different problems.

Lazy initialization runs your function once, during component mount, to calculate the initial state value. It prevents expensive computations from running on every single render when React calls your component function.

useMemo (which you'll learn later) runs during re-renders to avoid recalculating derived values when dependencies haven't changed. It optimizes what happens after the first render.

The Timeline Difference

Think of it like building a house:

  • Lazy init is choosing expensive materials only once when you build the foundation (mount)
  • useMemo is reusing cleaned windows instead of washing them again every day (re-renders)
// Lazy init: runs ONCE at mount
const [data, setData] = useState(() => {
  return JSON.parse(localStorage.getItem('bigData')); // Only once!
});

// useMemo would run on EVERY re-render where deps change

When You Need Each

Use lazy initialization when the problem is: "My component is slow to mount because calculating initial state is expensive."

Use useMemo (future lesson) when the problem is: "My component re-renders are slow because I'm recalculating the same value."

They're not interchangeable—you might even use both in the same component for different purposes.

Key Takeaway: Lazy initialization optimizes the first render (mount), while useMemo optimizes subsequent renders. They target different phases of the component lifecycle.