Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 50 ยท Data Mode

Lazy Routes and Code Splitting

Split your app into per-route bundles with route.lazy and React.lazy, preload pages on hover, avoid layout flashes, and handle chunk load failures in React Router.

A single-page app starts by downloading JavaScript, and the more routes you add, the more it has to download before the first screen appears. A visitor to the home page pays for the admin dashboard, the charting library and the rich-text editor, none of which they have asked for. The cure is code splitting: build each route (or group of routes) into its own file, and download it only when someone navigates there.

Routing is the natural place to split, because a route is exactly the unit of "something the user asks for". React Router supports it in two ways: the lazy property of a route object in a data router, and plain React.lazy with Suspense, which also works in declarative mode. In this lesson you will use both, compare how they behave while a chunk downloads, add preloading so the chunk is often already there when the user clicks, and learn how to avoid layout flashes and what to do when a chunk fails to load.

How the splitting works

The splitting itself is done by your bundler (Vite, webpack, Rollup...), not by React Router. The bundler treats every dynamic import() as a split point: the imported file and everything only it needs become a separate chunk, downloaded on demand.

flowchart LR
    A["main bundle<br/>(shell, home, router)"] -->|"import('./routes/reports')"| B["reports chunk<br/>(chart library)"]
    A -->|"import('./routes/settings')"| C["settings chunk"]
    A -->|"home route, static import"| D["Home stays in main"]

Only what the first screen needs ships in the main bundle. Each dynamic import becomes its own downloadable chunk.

Code you load with a normal import at the top of a file is part of the importing bundle. That is why splitting is something you do deliberately, route by route.

route.lazy in a data router

In a data router, a route can say "my real definition lives in another file" with lazy. It is a function that returns a promise of the pieces of the route:

JSX
// router.jsx - React Router (read-only)
import { createBrowserRouter } from 'react-router';
import Root from './root';
import Home from './home';

export const router = createBrowserRouter([
  {
    path: '/',
    Component: Root,
    children: [
      { index: true, Component: Home },
      { path: 'reports', lazy: () => import('./routes/reports') },
      { path: 'settings', lazy: () => import('./routes/settings') },
    ],
  },
]);

The imported module exports the route's parts under the names the router expects:

JSX
// routes/reports.jsx - React Router (read-only)
import { useLoaderData } from 'react-router';
import { BigChart } from '../charts'; // heavy library, only in this chunk

export async function loader() {
  const response = await fetch('/api/reports');
  return response.json();
}

export function Component() {
  const reports = useLoaderData();
  return <BigChart data={reports} />;
}

export function ErrorBoundary() {
  return <p>Reports could not be loaded.</p>;
}

The module can export Component, loader, action, ErrorBoundary, handle, shouldRevalidate and a few others, the same properties a route object accepts directly. You can also return an object yourself from the lazy function to rename things. Newer 7.x releases additionally let lazy be an object with one function per property, so the loader code and the component code can be fetched separately. Properties that define the shape of the tree (path, index, children) stay in the main bundle, because the router has to match URLs before it knows anything else. Do not define the same property both on the route and in the lazy module.

What matters most is when the chunk is fetched: during the navigation, before the route renders. The router keeps the current page on screen, useNavigation().state is "loading" (so your progress bar works), and when the module is ready the new route appears fully formed. A route with a static loader on the route object starts that loader in parallel with the chunk download, which is a good reason to keep the data fetch in the main bundle when the page's data matters more than its code size.

Real library or stand-in? The react-router and React.lazy code blocks are the real APIs. The live examples run in a sandboxed preview that cannot import your files or install packages, so they replace import('./routes/reports') with a fake import: a function that waits 900 ms, counts the download, remembers the result the way a browser module cache does, and returns the route's pieces. The router around it is a small hand-written one on React and location.hash. React.lazy and Suspense in the second example are the genuine React ones.

route.lazy stand-in with preloading

Try it twice. First without preloading: click "Reports" and the old page stays, dimmed, with navigation.state at loading for 900 ms. Click "Reports" again later and it is instant, because the chunk is cached. Then reload the example, tick "Preload", hover over "Settings" for a second and click it: the page appears at once, since the download began when the pointer arrived. Note that the old page never turned into a spinner or a blank screen.

sequenceDiagram
    participant U as User
    participant R as Router
    participant N as Network
    U->>R: hover link (optional preload)
    R->>N: start the chunk download early
    U->>R: click link
    R->>N: need route module (and static loader)
    N-->>R: chunk ready
    R->>U: render the new route in one step

With preloading the download starts at hover. By the time the click arrives, the chunk is often already there.

Preloading

Splitting trades bundle size for a delay at click time. Preloading wins the delay back by starting the download before the click. Good triggers are hovering or focusing a link (people hover for a few hundred milliseconds before they click), or the moment the page is idle, for routes the user is likely to visit next.

In a data router you preload by calling the same dynamic import yourself. The browser fetches the module once, so when the router calls lazy it gets the cached module:

JSX
// nav-link.jsx - React Router (read-only)
import { NavLink } from 'react-router';

const preloaders = {
  '/reports': () => import('./routes/reports'),
  '/settings': () => import('./routes/settings'),
};

export function PreloadingLink({ to, children }) {
  const preload = () => preloaders[to]?.();
  return (
    <NavLink to={to} onMouseEnter={preload} onFocus={preload}>
      {children}
    </NavLink>
  );
}

In framework mode (see Framework Mode Overview) the build splits routes automatically, and <Link prefetch="intent"> does this hover preloading for you, for the chunk and the data. Data mode has no such prop, so the snippet above is the pattern. Newer 7.x releases also offer patchRoutesOnNavigation for very large apps, where whole branches of the route tree are discovered and added lazily; reach for it only when the route config itself has become big.

React.lazy: the declarative-mode way

Without a data router, there is no lazy property and no navigation object. You split with React's own tool and show a fallback while the chunk downloads:

JSX
// App.jsx - React Router declarative mode + React (read-only)
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router';

const Reports = lazy(() => import('./routes/Reports')); // needs a default export

export default function App() {
  return (
    <Routes>
      <Route path="/" element={<Layout />}>
        <Route index element={<Home />} />
        <Route
          path="reports"
          element={
            <Suspense fallback={<p>Loading reports...</p>}>
              <Reports />
            </Suspense>
          }
        />
      </Route>
    </Routes>
  );
}

This differs from route.lazy in a way users can see: route.lazy holds the old page until the new one is ready, while React.lazy navigates immediately and shows the fallback in the new route's place. Neither is wrong, but a fallback that shows for a fraction of a second is a flash, and a fallback in the wrong place is a big flash. The second example makes the placement visible.

React.lazy, Suspense placement and the download counter

Click "Show chart" with the checkbox off: the header stays and only the content area shows "Loading chart..." for 900 ms. Hide the chart and show it again: it appears instantly and the download counter stays at 1, because a lazy component loads once. "Forget the download" creates a fresh lazy component, so the next show downloads again. Now tick the checkbox and show the chart: the header disappears and "Loading the whole page..." replaces everything, which is exactly the layout flash you want to avoid.

Avoiding layout flashes

  • Put Suspense as low as makes sense, around the content area that changes, never around the whole layout. Header, sidebar and footer then stay put.
  • Prefer route.lazy in a data router when you want the old page to stay until the new one is ready; there is no fallback to flash at all.
  • Preload likely next routes on hover, focus or idle time, so the fallback rarely appears.
  • Use a skeleton, not a spinner, if a fallback must show: a placeholder with the final layout's size avoids jumps.
  • Give fallbacks a delay. A fallback that appears only after 150 ms makes fast loads invisible.
  • Consider transitions. React can keep already-visible content while a new part suspends if the update is a transition (see Transitions). React Router v7 applies router state updates with startTransition, which helps for boundaries that are already on screen.

What to split, and what not to

Split routes that are large and rarely visited: an admin area, a settings section, a page with a charting library, a rich-text editor, a map. Keep the entry route and anything on the typical first-click path in the main bundle, because splitting a 3 KB page costs more in extra requests than it saves. Too many tiny chunks also create waterfalls: a chunk that imports another chunk that imports a third is three sequential round trips. Check your bundle with your tool's analyzer rather than guessing; the code splitting lesson covers the general approach.

When a chunk fails to load

Chunk files have hashed names. If you deploy a new version while someone has the old one open, the old chunk URL may be gone, and the dynamic import fails with an error such as "Failed to fetch dynamically imported module". Their network may also simply drop. With route.lazy the rejection goes to the route's ErrorBoundary (see Error Boundaries and Error Elements); with React.lazy it goes to the nearest React error boundary. Give those boundaries a "Reload page" button, because a reload picks up the new HTML and the new chunk names.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In a data router, what does a route's lazy property return?

    lazy is a function returning a promise (usually a dynamic import) of an object or module with the route's Component, loader, action, ErrorBoundary and similar exports.
  2. 2. How does the page behave while a route.lazy module downloads?

    The router resolves the lazy module (and loader) during the navigation, so the new route renders in one step. There is no fallback to flash.
  3. 3. Where is the best place for a Suspense boundary around a React.lazy route?

    The fallback replaces everything inside the nearest Suspense, so a low boundary around only the changing content avoids a full-page flash.
  4. 4. How can you make a lazy route feel instant for most users?

    Calling the same import() early lets the browser download and cache the chunk, so the router's later call resolves immediately. Splitting everything would create waterfalls.
  5. 5. What does React.lazy require from the module you import?

    React.lazy expects the promise to resolve to an object with a default export. route.lazy is different: it looks for named exports like Component and loader.

Summary

  • Code splitting is done by the bundler at dynamic import(); routes are the natural place to split.
  • In a data router, lazy: () => import('./route') loads a module that exports Component, loader, ErrorBoundary and friends during navigation, keeping the old page visible.
  • In declarative mode use React.lazy with Suspense; the fallback shows in the new route's place, so keep the boundary low.
  • Preload on hover, focus or idle time by calling the same import early; framework mode does this with prefetch="intent".
  • Split large, rarely visited routes; avoid tiny chunks and import waterfalls.
  • Handle chunk load failures with an error boundary that offers a page reload.

Next: Scroll Restoration, Focus and Page Titles