Sub topic 14
Splitting Code by Route
This chapter assumes you can build React components with hooks, use React Router, and run a bundler such as Vite or webpack. It also assumes the feature-module layout from earlier chapters, where each feature has an index.ts as its public API.
Why split by route
A bundler by default produces one JavaScript file for the whole app. Every visitor downloads the code for every page, including pages they never open. As the codebase grows, the first load gets slower.
Code splitting breaks the build into several files called chunks. The browser loads the main chunk first and fetches other chunks when needed. Routes are the most natural split point, because a user sees one route at a time and a route change is already a loading moment.
The bundler does the splitting. It looks for dynamic import() calls, which return a promise, and puts the imported module and its exclusive dependencies in a separate chunk. Your job is to decide where those calls go.
Lazy loading a route with React.lazy
React.lazy takes a function that returns a dynamic import and gives you a component. Suspense shows a fallback while the chunk loads.
import { lazy, Suspense } from "react";
import { Route, Routes } from "react-router-dom";
const SettingsPage = lazy(() => import("@/features/settings/SettingsPage"));
export function AppRoutes() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Routes>
<Route path="/settings" element={<SettingsPage />} />
</Routes>
</Suspense>
);
}Three details matter here:
React.lazyexpects the imported module to have a default export. Named exports need an adapter, shown below.- The
lazy()call must be at module level, not inside a component. Inside a component it creates a new lazy type on every render and the chunk state resets. Suspensemust be an ancestor of the lazy component. Without one, React throws an error.
Lazy loading and public APIs
A feature's index.ts is its public API, and the lint rule from the boundary chapter forbids importing past it. Lazy loading appears to conflict with this. The example above imports SettingsPage from @/features/settings/SettingsPage, which is an internal path.
There is a second problem. If you import a feature's index.ts normally, the bundler pulls in everything that index re-exports. When the index exports the page along with several other things, a static import of any one name can drag the whole feature into the main chunk.
A clean approach is to make the lazy entry point part of the public API. Give the feature a small file that exports only the page, and import that file dynamically:
// src/features/settings/routes.ts
export { SettingsPage } from "./components/SettingsPage";// src/app/routes.tsx
import { lazy } from "react";
const SettingsPage = lazy(() =>
import("@/features/settings/routes").then((m) => ({
default: m.SettingsPage,
}))
);The .then call converts a named export into the { default } shape that React.lazy requires. The lint pattern @/features/*/* would still flag this import, so add routes.ts as an allowed exception for files under src/app. A flat-config override can do this:
// eslint.config.js (add after the existing rules)
export default [
{
files: ["src/app/routes.tsx"],
rules: {
"no-restricted-imports": "off",
},
},
];Turning the rule off for one file is coarse, but that file is the only place where route entry points are wired. Keep it small so this exception stays easy to review.
What goes in the main chunk
Splitting only helps if the main chunk stays small. Watch for these causes of accidental inclusion:
- A static import elsewhere. If
App.tsximports anything from@/features/settingsnormally, the settings code lands in the main chunk, and the lazy import saves nothing. A dynamic import only creates a separate chunk when no static import reaches the same module. - Barrel files. An
index.tsthat re-exports many modules can pull them all in. Prefer the narrowroutes.tsentry for lazy loading. - Shared code. Code used by several routes is placed in a shared chunk automatically. That is correct behavior, not a bug.
Check the result instead of guessing. Vite users can run npx vite build and read the chunk list in the output. For a visual map, add a plugin such as rollup-plugin-visualizer. Webpack users can use webpack-bundle-analyzer.
Choosing which routes to split
Not every route deserves its own chunk. Use these rules of thumb:
| Route type | Split? | Reason |
|---|---|---|
| Landing page or the first screen most users see | No | It is needed immediately, so splitting adds a second request |
| Large, rarely visited page (settings, admin) | Yes | Most users never pay for it |
| Page with a heavy library (charts, editors, maps) | Yes | The library dominates the chunk size |
| Tiny page with few dependencies | Usually no | The extra request costs more than the bytes saved |
Each chunk adds a network request. Splitting a 2 KB page is a net loss.
Loading states and errors
While a chunk loads, Suspense shows its fallback. A single fallback at the top replaces the whole screen, including the navigation bar, which feels jarring. Place the Suspense boundary around the route content only, inside the layout:
import { lazy, Suspense } from "react";
import { Outlet, Route, Routes } from "react-router-dom";
const ReportsPage = lazy(() => import("@/features/reports/routes").then((m) => ({ default: m.ReportsPage })));
function Layout() {
return (
<div>
<nav>{/* navigation links */}</nav>
<Suspense fallback={<p>Loading page...</p>}>
<Outlet />
</Suspense>
</div>
);
}
export function AppRoutes() {
return (
<Routes>
<Route element={<Layout />}>
<Route path="/reports" element={<ReportsPage />} />
</Route>
</Routes>
);
}Now the navigation stays visible and only the page area shows the fallback.
Chunk loading can also fail. The user may be offline, or you may have deployed a new version that deleted the old chunk file while the user still had the old page open. A failed dynamic import rejects the promise, and React raises it as an error during render. Wrap the routes in an error boundary so users see a message and a reload option instead of a blank screen. After a deployment, a full page reload fetches the new main chunk and fixes stale references.
Preloading
A lazy route has a delay on first visit. You can hide it by starting the download early. Because import() is just a function call, you can call it before the user navigates, for example when they hover over a link:
const loadReports = () => import("@/features/reports/routes");
export function ReportsLink() {
return (
<a href="/reports" onMouseEnter={loadReports} onFocus={loadReports}>
Reports
</a>
);
}The browser caches the module, so a repeated call does not download it again, and React.lazy reuses the resolved module. In a real app, use the router's Link component with the same handlers.
Router-level lazy loading
React Router 6.4 and later, using a data router such as createBrowserRouter, supports a lazy property on route objects. It loads the route's component and loader together, and it does not need React.lazy or a Suspense wrapper for the route itself:
import { createBrowserRouter } from "react-router-dom";
export const router = createBrowserRouter([
{
path: "/settings",
lazy: async () => {
const { SettingsPage } = await import("@/features/settings/routes");
return { Component: SettingsPage };
},
},
]);Choose this form if you already use a data router. It also lets the router start loading data while the chunk downloads, which avoids a waterfall where code loads first and data requests start only afterward.
Common errors
- "A component suspended while responding to synchronous input." A lazy component rendered during an urgent update without a Suspense boundary above it. Add the boundary.
- Element type is invalid, got undefined. The module has no default export. Add a
.thenadapter or a default export. - No size reduction. A static import elsewhere includes the module in the main chunk. Search for imports of that feature and check the bundle report.
- Alias works in dev, fails in build. The bundler's alias setting does not match the
tsconfigpathsentry. Configure both.
Exercise
Your app's main chunk is still large after you convert the Reports page to React.lazy. The bundle report shows the reports code inside main.js. Name two likely causes and how to check each.
Show answer
First, another file statically imports from the reports feature, for example App.tsx importing a component from @/features/reports. A dynamic import only makes a separate chunk when no static import reaches the same module, so search the project for imports of the feature and replace them with the lazy entry or remove them. Second, the lazy import targets a barrel index.ts that is also imported statically elsewhere, or that re-exports unrelated modules. Point the dynamic import at a narrow routes.ts file and confirm with the bundle visualizer that the reports modules now sit in their own chunk.
Exercise
Why should the Suspense boundary sit around <Outlet /> in a layout instead of around the whole <Routes> tree?
Show answer
A boundary around the whole tree replaces everything, including the navigation, with the fallback each time a chunk loads. A boundary around <Outlet /> keeps the layout visible and shows the fallback only where the page content will appear.