What is code splitting?
Code splitting divides your JavaScript bundle into smaller chunks that load on demand, so users download only the code for what they are viewing. Bundlers (Vite with Rolldown, webpack, Turbopack) create a chunk at every dynamic import(); React uses this through React.lazy, and routers and frameworks split per route automatically.
Split points
- Routes: the biggest win. Each page in its own chunk.
- Heavy components: charts, editors, maps, date pickers, rendered only when needed.
- Libraries used rarely: PDF export, spreadsheet parsing, syntax highlighting.
- Vendor chunks: bundlers split shared dependencies so they are cached across routes.
How it works
import("./Chart") returns a promise. The bundler emits Chart and its dependencies as a separate file and loads it when the promise is created. lazy turns that promise into a component that suspends until loaded.
Frameworks
- Next.js: automatic per-route splitting; Server Components send no JavaScript for themselves.
- React Router (framework or data mode): route modules and
lazyroute properties. - Vite SPA: add
lazy()at route boundaries.
Trade-offs
- Too many tiny chunks add request overhead.
- Users may wait on navigation; prefetch likely routes on hover or idle.
- Handle chunk load failures after deployments with an error boundary that offers a reload.
Measuring
Bundle analyzers (rollup-plugin-visualizer for Vite, @next/bundle-analyzer or next analyze) show chunk contents.
Code example
1import { lazy, Suspense } from "react";2import { createBrowserRouter } from "react-router";3import { RouterProvider } from "react-router/dom";45// Each page becomes its own chunk6const Home = lazy(() => import("./pages/home"));7const Settings = lazy(() => import("./pages/settings"));8const Reports = lazy(() => import("./pages/reports")); // includes a heavy chart library910function Page({ children }: { children: React.ReactNode }) {11 return <Suspense fallback={<p>Loading page…</p>}>{children}</Suspense>;12}1314const router = createBrowserRouter([15 { path: "/", element: <Page><Home /></Page> },16 { path: "/settings", element: <Page><Settings /></Page> },17 { path: "/reports", element: <Page><Reports /></Page> },18]);1920export function App() {21 return <RouterProvider router={router} />;22}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.