← Lessons

quiz vs the machine

Gold1400

Frontend

The Code Splitting React Lazy

Split the bundle and load components only when they are needed.

5 min read · core · beat Gold to climb

Why split the bundle

A single large JavaScript bundle delays the first paint because the browser must download and parse it all before anything runs. Code splitting breaks the bundle into smaller chunks loaded on demand.

  • A dynamic import creates a separate chunk at the import point
  • The chunk downloads only when that code path runs
  • This shrinks the initial bundle and speeds up first load

React lazy

React lazy turns a dynamic import of a component into a lazily loaded component. The bundler emits a separate chunk, and React fetches it the first time the component renders.

  • Wrap the lazy component in a Suspense boundary for the loading state
  • Common split points are routes and rarely used heavy widgets
  • A failed chunk load should be handled with an error boundary

Trade offs

Splitting too finely creates many tiny requests. Group related code so each chunk is worth its own round trip.

Loading a chunk

Key idea

Code splitting with dynamic imports and React lazy keeps the initial bundle small by loading components as separate chunks on demand, paired with a Suspense fallback for the wait.

Check yourself

Answer to earn rating on the learn ladder.

1. What does React lazy do with a dynamic import of a component?

2. What must wrap a React lazy component to handle its loading delay?

3. What is a downside of splitting the bundle too finely?