Sub topic 6
Splitting by route
This chapter assumes you can write function components, you know React.lazy and Suspense from the earlier chapters, and you have a React Router v6 or later app built with a bundler such as Vite or webpack. Here you apply those tools at the level where they usually pay off most: one chunk per page.
Why routes are the natural split point
Code splitting helps only if the user doesn't need the split code right away. A route is a good boundary for three reasons.
- Routes are mutually exclusive. A visitor on
/doesn't need the code for/settingsuntil they navigate there. - Routes are large. A page usually pulls in its own components, helpers, and often a heavy library such as a chart or editor. The saving per split is therefore large.
- Navigation is a loading moment users already expect. A short wait after a click reads as normal. A short wait inside a page you're already using feels like a bug.
Splitting individual components, such as a modal or a chart, still helps. Start with routes, then split further only where a measurement shows a heavy component.
The basic pattern
Each page component is loaded with lazy and a dynamic import(). The bundler sees every import() call and emits the target module, plus anything only it uses, as a separate chunk.
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Settings = lazy(() => import('./pages/Settings'));
export default function App() {
return (
<BrowserRouter>
<Suspense fallback={<p>Loading page...</p>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}A single Suspense boundary above Routes covers every page. It's the smallest setup that works, but it has a weakness, covered in the next section.
Two rules apply to the lazy calls themselves.
- Call
lazyat module top level. If you call it inside a component, every render creates a new component type. React then discards the loaded component and its state, and loads it again. - The module must have a default export. If a page has only a named export, map it inside the import promise:
import { lazy } from 'react';
// pages/Settings.jsx has: export function Settings() { ... }
const Settings = lazy(() =>
import('./pages/Settings').then((module) => ({ default: module.Settings }))
);What the build produces
After vite build, each dynamic import becomes its own file. The output looks like this (the names and sizes are illustrative):
dist/assets/index-3f9a1c.js 82.4 kB entry: React, router, Layout
dist/assets/Home-a81b22.js 6.1 kB Home page code
dist/assets/Settings-c70d9e.js 41.7 kB Settings page and its form library
dist/assets/vendor-9b2e44.js 28.3 kB code shared by Home and SettingsThe bundler also extracts modules that several chunks import into a shared chunk, so they aren't duplicated. Because of this, splitting by route doesn't make your total download much larger. It changes when each piece downloads.
Place the boundary inside the layout
With one boundary above Routes, a navigation to an unloaded page replaces everything under that boundary with the fallback. That includes the navigation bar and the sidebar. The whole screen flashes to "Loading page..." and then redraws.
A better arrangement keeps the layout outside the boundary and suspends only the page area. Use a layout route and put Suspense around Outlet:
import { lazy, Suspense } from 'react';
import { BrowserRouter, Routes, Route, Link, Outlet } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Settings = lazy(() => import('./pages/Settings'));
const NotFound = lazy(() => import('./pages/NotFound'));
function Layout() {
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/settings">Settings</Link>
</nav>
<main>
<Suspense fallback={<p>Loading page...</p>}>
<Outlet />
</Suspense>
</main>
</div>
);
}
export default function App() {
return (
<BrowserRouter>
<Routes>
<Route element={<Layout />}>
<Route index element={<Home />} />
<Route path="settings" element={<Settings />} />
<Route path="*" element={<NotFound />} />
</Route>
</Routes>
</BrowserRouter>
);
}Layout is part of the entry bundle, so the navigation renders immediately and stays on screen. Only the main area shows the fallback.
For a dashboard with nested layouts, repeat the idea. Each layout that has its own child pages can have a Suspense boundary around its own Outlet. A navigation inside /settings/* then suspends only the inner panel, and the outer shell stays put.
Which routes to split
Not every route should be lazy.
| Route type | Split it? | Reason |
|---|---|---|
| Landing page that most visitors open first | Usually not | Making it lazy adds a request after the entry bundle. The fastest first render needs it in the entry bundle. |
| Rarely visited pages (settings, admin, billing) | Yes | Most visitors never need them. |
| Pages with heavy dependencies (charts, editors, maps) | Yes | The saving is largest here. |
| Tiny pages (a 404 screen) | Optional | A chunk under a few kilobytes costs a request and saves little. |
A lazy entry route also creates a request waterfall. The browser downloads the entry bundle, runs it, discovers it needs Home, and only then requests the Home chunk. If most users land on a given route, keep it eager or preload it, as described below.
Handling load failures per route
A route chunk is a network request, so it can fail. The user may lose connectivity. More often, you deploy a new version, and the old hashed file names no longer exist on the server. A tab that was open before the deploy then requests a chunk that returns a 404.
The dynamic import rejects, lazy rethrows during render, and without an error boundary React unmounts the whole tree. Put an error boundary around the Suspense boundary. Reuse the ErrorBoundary class from the previous chapter, saved here as ErrorBoundary.jsx:
import { Suspense } from 'react';
import { Outlet, useLocation } from 'react-router-dom';
import { ErrorBoundary } from './ErrorBoundary';
export function Layout() {
const location = useLocation();
return (
<main>
<ErrorBoundary
key={location.pathname}
fallback={
<p>
This page could not be loaded.{' '}
<button onClick={() => window.location.reload()}>Reload</button>
</p>
}
>
<Suspense fallback={<p>Loading page...</p>}>
<Outlet />
</Suspense>
</ErrorBoundary>
</main>
);
}Two details matter here.
- The
keyresets the boundary on navigation. An error boundary keeps its error state until it unmounts. Without the key, one failed page would show the error message for every later route, even ones that would load fine. Changing the key remounts the boundary with a clean state. - A reload is the right recovery after a deploy. Retrying the same import usually fails again, because the browser caches the rejected promise for that URL. A full reload fetches the new HTML, which points at the new chunk names.
Keep the current page during navigation
Even with the boundary inside the layout, a click on a link replaces the current page with the fallback while the chunk downloads. Often it's nicer to stay on the current page until the next one is ready. A transition does that: React keeps the already visible content on screen instead of showing a fallback for it.
Router navigation can run inside a transition. In React Router v6 this is opt-in through the v7_startTransition future flag, and React Router v7 enables it by default. With a recent version, set the flag like this:
import { BrowserRouter } from 'react-router-dom';
<BrowserRouter future={{ v7_startTransition: true }}>
{/* routes */}
</BrowserRouter>Behavior depends on your router version, so check your router's documentation. If your router doesn't wrap navigation in a transition, you can wrap a state change yourself with useTransition, as in the tabs example from the transitions chapter.
Preload the next page
A click that triggers a 40 kB download feels slow on a weak connection. You can start the download earlier, on hover or focus, which usually happens a few hundred milliseconds before the click. Keep the loader function in one place and share it between lazy and the link:
// routeModules.js
import { lazy } from 'react';
export const loadSettings = () => import('./pages/Settings');
export const Settings = lazy(loadSettings);// NavLinkWithPreload.jsx
import { Link } from 'react-router-dom';
export function NavLinkWithPreload({ to, load, children }) {
return (
<Link to={to} onMouseEnter={load} onFocus={load}>
{children}
</Link>
);
}
// Usage:
// <NavLinkWithPreload to="/settings" load={loadSettings}>Settings</NavLinkWithPreload>Calling loadSettings more than once is safe. The bundler's module system returns the same module after the first load, so repeated hovers don't trigger repeated downloads. lazy then finds the module already available and renders without suspending.
You can also preload when the browser is idle, for example calling loadSettings() inside requestIdleCallback after the first render. That works well for routes that most users visit second.
Router-native lazy routes
If you use a data router (createBrowserRouter), React Router offers a lazy property on the route object instead of React.lazy. The router loads the route module, including its loader and component, before it renders the route. The router then controls the pending state, so you read it with the router's navigation hooks and don't need a Suspense boundary for the page itself. This avoids a loader-then-component waterfall. The trade-off is that it ties your splitting to one router's API, while React.lazy works with any router. The rest of this chapter's patterns use React.lazy and apply to every router.
Common mistakes
- Calling
lazyinside a component. This resets state and reloads on every render. Move it to module scope. - Forgetting the default export. The error appears when the page first renders. Map named exports in the import promise.
- Wrapping everything in one top-level boundary. The navigation and layout disappear on every page change. Put the boundary around
Outlet. - No error boundary. One failed chunk blanks the app.
- Splitting the page every user lands on. This adds a waterfall to the most common visit. Keep it eager or preload it.
- Not checking the result. Splitting only helps if the entry bundle shrank. Compare build output before and after, and check the network panel in your browser's developer tools.
Exercise
Your app has a lazy Dashboard route and a lazy Reports route, with a single Suspense boundary wrapping the whole Routes element. Users complain that the sidebar flashes away whenever they click between the two. What change fixes this, and why does it work?
Show answer
Move the sidebar into a layout route that is not lazy, and put the Suspense boundary around the Outlet inside that layout. The layout lives in the entry bundle and sits outside the boundary, so it stays mounted. When a route chunk is still loading, only the content inside the Outlet boundary is replaced by the fallback.
Exercise
A user keeps a tab open, you deploy a new version, and then the user clicks a link to a lazy route. The page goes blank and the console shows a failed dynamic import. What happened, and what two things should the app do about it?
Show answer
The old tab requests a chunk by its old hashed file name, which no longer exists on the server, so the import rejects. Without an error boundary, React unmounts the tree. The app should wrap the Suspense boundary in an error boundary that shows a message with a reload button, because a reload fetches the new HTML with the new chunk names. The boundary should also be keyed by the route path so that its error state resets when the user navigates elsewhere.