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.