Sub topic 16
Code splitting by route
This chapter assumes you can define a router with createBrowserRouter, write route objects, and use loaders. You should also know what a dynamic import() is. Earlier chapters covered all of these.
Why split code by route
By default a bundler such as Vite or webpack combines every module reachable from your entry file into one JavaScript file. The browser must download and parse that whole file before the app is useful. Most visitors never open the admin screen or the reports page, yet they pay for that code.
Code splitting breaks the bundle into smaller files called chunks. The browser fetches a chunk only when it is needed. Routes are a natural place to split, because a URL change is a clear signal that the user needs a different screen.
The bundler splits code at every dynamic import() call. A dynamic import takes a path and returns a promise that resolves to the module.
const module = await import("./routes/reports");
console.log(Object.keys(module));React Router's lazy route property builds on this.
The lazy property
lazy is a function that returns a promise for a module. The router calls it when it matches the route, then reads the module's exports and uses them as route properties.
import { createBrowserRouter, RouterProvider } from "react-router-dom";
const router = createBrowserRouter([
{
path: "/reports",
lazy: () => import("./routes/reports"),
},
]);
export default function App() {
return <RouterProvider router={router} />;
}The lazy module is an ordinary file with named exports:
// routes/reports.jsx
import { useLoaderData } from "react-router-dom";
export async function loader() {
const res = await fetch("/api/reports");
if (!res.ok) {
throw new Response("Could not load reports", { status: res.status });
}
return res.json();
}
export function Component() {
const reports = useLoaderData();
return (
<ul>
{reports.map((r) => (
<li key={r.id}>{r.title}</li>
))}
</ul>
);
}
export function ErrorBoundary() {
return <p>The reports page failed to render.</p>;
}The router maps these export names to route properties:
| Export name | Equivalent route property |
|---|---|
| `Component` | `Component` (used instead of `element`) |
| `ErrorBoundary` | `ErrorBoundary` (used instead of `errorElement`) |
| `loader` | `loader` |
| `action` | `action` |
| `handle` | `handle` |
| `shouldRevalidate` | `shouldRevalidate` |
Note that Component takes a component reference, not a JSX element. That is why the export is Component, not element.
What lazy cannot define
Matching has to happen before the router knows which chunk to fetch. So these properties must stay in the route object and cannot come from the lazy module:
pathindexchildrenidcaseSensitive
Children can still be lazy. Each child route has its own lazy function. A parent layout can be eager while its heavy children load on demand:
import { createBrowserRouter } from "react-router-dom";
import Layout from "./Layout";
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, lazy: () => import("./routes/home") },
{ path: "reports", lazy: () => import("./routes/reports") },
{ path: "settings", lazy: () => import("./routes/settings") },
],
},
]);If a route defines a property statically and the lazy module also exports it, the static value wins. React Router also warns in development when the lazy module returns a property it will ignore.
What happens on navigation
When the user navigates to a lazy route, the router resolves the lazy function first, then runs the loader. It keeps the current screen visible until the data is ready. The new route renders only after both finish.
Because the old page stays on screen, you do not need a Suspense fallback for lazy routes. Use useNavigation to show a pending indicator, as in the earlier pending UI chapter:
import { Outlet, useNavigation } from "react-router-dom";
export default function Layout() {
const navigation = useNavigation();
return (
<div>
{navigation.state === "loading" && <p role="status">Loading...</p>}
<Outlet />
</div>
);
}The chunk and data waterfall
If the loader lives inside the lazy module, the browser must download the chunk before the loader can even start. The data request waits behind the code request. That is a waterfall.
You can avoid it by keeping the loader in the route object and lazy-loading only the component. A statically defined loader can run while the chunk downloads:
const router = createBrowserRouter([
{
path: "/reports",
loader: async () => {
const res = await fetch("/api/reports");
return res.json();
},
lazy: async () => {
const { Component } = await import("./routes/reports-view");
return { Component };
},
},
]);The trade-off: the loader code is now in the main bundle. Loaders are usually small, since they mostly call fetch, so this is often worthwhile for slow endpoints.
Alternative: React.lazy with Suspense
You can also use React.lazy. It splits a component rather than a route, so the router does not know about the chunk until the component renders.
import { lazy, Suspense } from "react";
import { createBrowserRouter } from "react-router-dom";
const Reports = lazy(() => import("./components/Reports"));
const router = createBrowserRouter([
{
path: "/reports",
element: (
<Suspense fallback={<p>Loading reports...</p>}>
<Reports />
</Suspense>
),
},
]);| Concern | `lazy` route property | `React.lazy` |
|---|---|---|
| Split unit | Whole route (component, loader, action) | One component |
| Old page stays visible | Yes | No, the fallback replaces the content |
| Needs `Suspense` | No | Yes |
| Component needs a default export | No, uses `Component` | Yes |
Prefer the route property when you use a data router. Use React.lazy for heavy components that are not tied to a route, such as a chart or editor.
Verifying the split
Do not assume the split worked. Run a production build and check the output. With Vite:
npm run buildThe build log lists one JavaScript file per chunk, for example a separate reports-*.js. In the browser's Network tab, load / and confirm the reports chunk is not requested until you navigate to /reports.
A common cause of a missing split is an extra static import of the same module elsewhere. If Layout.jsx has import { formatDate } from "./routes/reports", the bundler puts that module in the main chunk, and the dynamic import no longer creates a separate file.
Common errors
- Using a default export.
lazyreads named exports. A module with onlyexport default function Reports()gives the router nothing to render. Export it asComponent. - Putting
pathin the lazy module. The router ignores it, so the route never matches. - Splitting everything. Tiny routes produce tiny chunks, and each costs a network round trip. Split large or rarely visited routes, and keep the home page and layout in the main bundle.
- Ignoring failed chunk loads. After a new deploy, an open tab may request a chunk file that no longer exists. The import rejects, and the router sends the error to the nearest error boundary. Provide an
errorElementon a parent route so users see a message, and consider offering a reload button.
Exercise
A route is defined as { path: "/billing", lazy: () => import("./routes/billing") }, but routes/billing.jsx only has export default function Billing() { ... }. The page renders nothing useful. What is wrong, and how do you fix it?
Show answer
The lazy property reads named exports such as Component, loader, and action, and does not use the default export. Change the file to export function Component() { ... } (and rename or alias Billing accordingly). The route then renders the component.
Exercise
Your reports route has a slow API call. The chunk takes 300 ms to download and the API takes 500 ms to answer. The loader is exported from the lazy module. Roughly how long until the data is ready, and how can you shorten it?
Show answer
About 800 ms, because the loader cannot start until the chunk has loaded, so the two times add up. Define the loader statically on the route object and lazy-load only the component. The loader then runs while the chunk downloads, and the wait drops to about 500 ms, the longer of the two.