Deploying React AppsEntry 2 of 11
Lazy Loading Components with lazy()
React.lazy() loads a component's code only when it's first rendered, instead of bundling it into the initial download.
react.devlazy
Notes
- By default, every imported component ends up in one bundle that the browser downloads before showing anything.
- Lazy loading splits the code: pages users may never visit are downloaded only when needed.
- Change the static import to
lazy(() => import('./pages/Blog')). import()(the function) returns a Promise, which bundlers like Vite use as a split point, creating a separate file.- The lazy-loaded module must have a default export of the component.
- A lazy component must render inside
<Suspense>(Entry 4).
What / Why / When
- What
On-demand component code.
- Why
A smaller initial bundle means a faster first page load.
- When
Large pages, routes users rarely visit, heavy widgets (charts, editors).
Code compare
// ❌ Before: static import, included in the main bundleimport BlogPage from "./pages/Blog";// Lazy route component{ path: 'posts', loadComponent: () => import('./pages/blog.component').then((m) => m.BlogComponent),}Differences and gotchas
React.lazy()requires a default export. Angular'sloadComponentworks with named exports via.then(m => m.X), or with a default export directly.- ❌ Don't call
lazy()inside a component; it creates a new component on every render and resets state. Define it at module level.
Quick reference
| React | Angular |
|---|---|
lazy(() => import('./Page')) | loadComponent: () => import('./page.component').then(m => m.PageComponent) |
| — | loadChildren for route groups |
| Default export required | Named or default export |