Code Splitting and Lazy Loading
On this page
Why Code Splitting Matters
- Large bundles delay first interaction.
- Users rarely need the entire application on first load.
- Split by route and by heavy feature modules.
Route Level Splitting
- Lazy load page components.
- Keep layout shell eagerly loaded.
- Prefetch likely next routes when idle.
Example: React.lazy
const AdminPage = React.lazy(() => import("./AdminPage"));
function App() {
return (
<React.Suspense fallback={<Spinner />}>
<AdminPage />
</React.Suspense>
);
}
Suspense Boundary Design
- Place boundaries around slow loading regions.
- Avoid wrapping entire app in one Suspense.
- Combine with error boundaries to catch load failures.
Prefetch Strategy
- Prefetch when link is visible or hovered.
- Prefetch based on user navigation patterns.
- Avoid overfetching large chunks unnecessarily.
Failure Modes
- Waterfall loading due to nested lazy imports.
- Single Suspense boundary blocking entire UI.
- Missing error boundaries causing blank screens.
- Chunk duplication from misconfigured bundler.
Deployment Checklist
- Analyze bundle size after build.
- Verify chunk caching headers.
- Ensure fallback UI is meaningful.
- Test slow network simulation.