Code Splitting
Code splitting splits the application bundle into smaller chunks loaded on demand using React.lazy and dynamic imports.
Mental Model
"The Just-In-Time Supply Chain: Instead of delivering 50 tons of brick on day 1, trucks deliver roof tiles only when the roof is ready."
Interactive Engine Walkthrough
Reference Code Snippet
1// Load component only when needed
2const HeavyProfile = React.lazy(() => import('./Profile'));
3
4function App() {
5 return (
6 <Suspense fallback={<Spinner />}>
7 <HeavyProfile />
8 </Suspense>
9 );
10}- 01.React.lazy takes a function that calls a dynamic import() and returns a component.
- 02.Always wrap lazy components in a <Suspense fallback={<Loader />}> boundary.
- 03.Great for heavy modal dialogs, complex charting libraries, and route-based code splitting.
01. Chunking the Universe
By default, your bundler (Vite/Webpack) creates one giant JS file. `React.lazy` allows you to split this into smaller "chunks." The browser only downloads the code for the current page, which makes the initial load significantly faster, especially on mobile.
Bundle Topography
02. Dynamic Imports
Lazy loading uses the ES6 `import()` syntax, which returns a Promise. React handles the resolving of this Promise and ensures that the component is ready before trying to render it. This is why `Suspense` is required—to tell React what to show while the file is downloading.
Senior Insight
"A great strategy is **Route-based splitting**. Every page in your app should be its own chunk. This ensures the user never downloads the code for the 'Settings' page if they only ever visit 'Home'."