Code Splitting: Optimize Bundle Size with Dynamic Imports
Learn the interview-ready mental model, practical trade-offs, and production patterns for this web fundamentals topic.
Topic content
Code splitting breaks your JavaScript bundle into smaller chunks that load on demand. It dramatically reduces initial load time by shipping only the code required for the current view. Use dynamic imports (`import()`) with React.lazy() and Suspense for seamless integration.
Instead of packing everything for every trip (large initial bundle), pack only what you need for today's journey (route) and open side pockets (heavy components) only when required. Dynamic imports let you unzip those pockets on demand.
1Route-Based Splitting
Automatically split by page/route. Each route becomes its own chunk, loaded only when the user navigates there.
const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
</Routes>
</Suspense>2Component-Based & Dynamic Imports
Split heavy components (charts, modals, editors) and load them conditionally on interaction or visibility.
3Vendor Splitting
Separate third-party libraries into their own chunk for better long-term caching since they change less frequently.
- ✓Code splitting reduces initial bundle size and improves LCP
- ✓Use React.lazy() + Suspense for easy route/component splitting
- ✓Dynamic imports enable conditional and on-demand loading
- ✓Separate vendor code for better caching
- ✓Always provide loading states and error boundaries
- ✓Measure bundle analyzer output and real-user performance
- ✓Balance splitting with user-perceived latency