Capítulo 87 de 116

Chapter 87: lazy

Core Idea

lazy(load) code-splits a component — instead of bundling it eagerly, its code chunk downloads only when it's first about to render, causing the nearest Suspense boundary to show its fallback while the download is in flight.

Key Concepts

  • Signature: const SomeComponent = lazy(() => import('./SomeComponent.js'))load is a function returning a promise that resolves to a module with a default export of the component.
  • Must render inside a Suspense boundary: a lazy component suspends (Ch 70) while its chunk is loading — without a Suspense ancestor to catch that, there's no fallback to show during the download.
  • The import() call is only made when first needed: React calls load() the first time it actually needs to render that component — not eagerly at module-evaluation time — which is what makes this a genuine code-splitting boundary rather than just an async wrapper.
  • Once loaded, stays loaded: the downloaded module is cached for the app's lifetime; subsequent renders of the same lazy component don't re-trigger the network request.
  • Common use: splitting rarely-visited routes/screens, heavy modals, or below-the-fold sections out of the initial bundle, so the app's first paint doesn't have to wait on code the user might never reach.

Code Examples

const MarkdownPreview = lazy(() => import('./MarkdownPreview.js'));

<Suspense fallback={<Spinner />}>
  <MarkdownPreview />
</Suspense>
  • What it demonstrates: the chunk for MarkdownPreview only downloads once this JSX actually attempts to render, with Spinner showing meanwhile.

Key Takeaways

  1. Always wrap a lazy-loaded component in a Suspense boundary — without one, there's nothing to show while its code downloads.
  2. The split point is determined by where you call lazy(() => import(...)), so place it around genuinely separable, non-critical-path pieces of the UI.
  3. Loading is triggered by first render attempt, not by module import — this is what actually defers the network request.

Connects To

  • Ch 70 (Suspense): the required boundary this component's loading state depends on.
  • Ch 6 (Build a React App from Scratch): code-splitting as one of the "common application patterns" a build tool doesn't solve for free.