As applications scale, their JavaScript bundle sizes often grow proportionally, leading to slower initial page loads and a degraded user experience. Code splitting is a fundamental optimization technique that addresses this by breaking your application's code into smaller, independent chunks, loading them only when they are actually needed. React.lazy offers a built-in, declarative way to implement code splitting at the component level. It allows you to render a dynamic import (e.g., import('./MyComponent')) as a regular React component, effectively instructing your bundler (like Webpack or Rollup) to create a separate JavaScript file for that component and its dependencies, which is then fetched on demand.
Key Takeaways
- Code splitting significantly reduces initial page load times by deferring non-essential code.
React.lazyenables dynamic importing, treating code-split components like regular React components.React.Suspenseprovides a user-friendly fallback UI while lazy components are loading.- Ideal for route-based splitting or conditionally rendered, large components (e.g., modals, admin panels).
Code Example
How this code works
This code demonstrates how to significantly improve an application's initial load time by only downloading code for components when they are actually needed. Specifically, it defers loading a potentially large component, MyBigComponent, until it's rendered, showing a temporary "Loading MyBigComponent..." message in the meantime. This technique is known as code splitting, preventing users from downloading unnecessary code upfront.
The core of this pattern involves lazy and Suspense from React. The lazy function takes an arrow function that returns a dynamic import() call for MyBigComponent. This import() is crucial; unlike regular static imports, it tells your bundler to create a separate file for MyBigComponent, which won't be part of the initial bundle. The Suspense component then wraps MyBigComponent. When MyBigComponent is first encountered and its code hasn't finished downloading, Suspense renders the element provided in its fallback prop. Once MyBigComponent's code is available, it replaces the fallback content and renders normally.