Code Splitting in React
Code splitting is breaking the bundle into pieces that load on demand (lazy loading).
React.lazy + Suspense
tsx
import { lazy, Suspense } from 'react';
const SettingsPage = lazy(() => import('./SettingsPage'));
function App() {
return (
<Suspense fallback={<PageSkeleton />}>
<SettingsPage />
</Suspense>
);
}Route-based splitting (React Router)
tsx
const router = createBrowserRouter([
{ path: '/', lazy: () => import('./HomePage') }, // module exports Component
{ path: '/dashboard', lazy: () => import('./DashboardPage') },
]);Tools
| Tool | Mechanism |
|---|---|
| Webpack | import() - automatic chunks |
| Vite | ESM-based splitting out of the box |
| Next.js | Automatic per page + dynamic() |
Webpack magic comments
tsx
const Chart = lazy(() =>
import(/* webpackChunkName: "chart" */ './Chart')
);Goal: send the user only the code needed for the current screen.
updated
did you know it?