📦 Code Splitting in React
Code splitting is a powerful optimization technique that allows you to split your code into smaller bundles that can be loaded on demand, improving initial load time and user experience.
❓ 1. Why Code Splitting?
- Reduce initial bundle size
- Load code only when needed
- Improve performance on slow networks
- Enable faster time-to-interactive
📂 2. Dynamic Import with React.lazy()
This is the most common approach to split components dynamically:
import React, { lazy, Suspense } from 'react';
const AboutPage = lazy(() => import('./pages/About'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<AboutPage />
</Suspense>
);
}
🛣️ 3. Route-Based Splitting
Works great with react-router
to load pages only when needed.
const Home = lazy(() => import('./pages/Home'));
const Contact = lazy(() => import('./pages/Contact'));
<Routes>
<Route path="/" element={<Home />} />
<Route path="/contact" element={<Contact />} />
</Routes>
✨ 4. Webpack Magic Comments
You can name your chunks for easier debugging:
const LazySettings = lazy(() => import(/* webpackChunkName: "settings" */ './Settings'));
📦 5. Other Tools & Libraries
- Loadable Components – SSR + Code Splitting
- React Loadable – older but effective
- Next.js – built-in automatic code splitting
✅ 6. Best Practices
- Split only large or infrequently used components
- Always wrap lazy components in
<Suspense>
- Use fallback spinners or skeleton loaders
- Test bundle size with Webpack Bundle Analyzer