Course contentsShow
← React
Lesson 1348 of 2,39634. Suspense FundamentalsFree lesson

What React.lazy() Does Under the Hood

Understand how React.lazy() creates a component that suspends while its module loads, throwing a promise React catches.

What React.lazy() Does Under the Hood

You'll learn: How React.lazy() transforms a dynamic import into a Suspense-compatible component that throws promises React can catch.

The Magic Trick Revealed

When you call React.lazy(), you're not directly creating a normal component. Instead, you're creating a special wrapper component that knows how to suspend.

Here's what happens under the hood:

  1. You provide a function that returns a dynamic import() statement
  2. React.lazy() wraps it in a component that manages loading states
  3. On first render, the wrapper executes your import function, which returns a Promise
  4. The wrapper literally throws that Promise (yes, throws it like an error!)
  5. React catches the thrown Promise instead of crashing
  6. React shows the nearest Suspense boundary's fallback while waiting
  7. When the Promise resolves, React retries rendering the component
  8. The actual component renders once the module is loaded

Think of It Like a Vending Machine

Imagine React.lazy() as a vending machine slot. You don't get your snack immediately—you get a "loading ticket" (the thrown Promise). The Suspense boundary is like the "Please Wait" light. When your snack (module) arrives, the machine (React) automatically delivers it to you.

The Promise-Throwing Pattern

This "throw a Promise" technique is how any Suspense-compatible library works. React.lazy() simply applies this pattern to code-splitting. The thrown Promise tells React: "I'm not ready yet, but I will be—just wait for this Promise to resolve."

Key Takeaway: React.lazy() creates a component that throws a Promise during its initial render, allowing React to suspend rendering and show a fallback until the dynamically imported module loads.