Sub topic 14
Splitting code by route
This chapter assumes you can build React components, use import and export, and run a bundler such as Vite or webpack. You should also know the basics of React Router and the feature layout from earlier chapters.
Why split by route
By default, a bundler combines your whole app into one JavaScript file. Users download code for the settings page even if they only visit the home page. Code splitting breaks that file into smaller chunks, and the browser loads each chunk when it needs it.
Routes are the natural place to split. A user sees one page at a time, so the code for other pages can wait. Feature modules make this easy because each feature already has a clear entry point.
Lazy loading a page
React.lazy takes a function that returns a dynamic import(). The bundler sees the dynamic import and creates a separate chunk for that file. Suspense shows a fallback while the chunk downloads.
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>
);
}The chunk for SettingsPage downloads the first time a user visits /settings. After that, the browser reuses it.
How the pieces fit together
Where to put the split
Put the lazy imports in one place, such as app/routes.tsx. This keeps the rest of your code unaware of splitting.
Splitting also interacts with the public API rule from earlier chapters. If a feature's index.ts re-exports every component, importing one name from it can pull the whole feature into the main bundle. For lazy pages, there are two common choices:
- Import the page file directly in the
lazycall, as in the example above. This is a deliberate exception to the index-only rule, so allow it in your lint config for route files. - Export the page from the feature's index and use
lazy(() => import("@/features/settings")), then pick the page from the module. This keeps the rule intact but loads everything the index exports, so it works best when the feature is small.
Common mistakes
- Creating the lazy component inside another component. Each render makes a new component type, so React remounts it and may refetch the chunk. Define
lazycalls at module level. - One
Suspensefor everything. A single top-level fallback replaces the whole screen during navigation. Place aSuspensearound the route outlet inside your layout so the header and navigation stay visible. - Splitting tiny pages. Each chunk costs an extra network request. Split large routes first, and check the bundle sizes before splitting more.
- No error handling. A chunk request can fail on a bad connection. Wrap lazy routes in an error boundary so users see a message and a retry option instead of a blank page.
Exercise
A teammate defines const Page = lazy(() => import("./Page")) inside the body of a layout component. Navigation to that route sometimes flashes the fallback again after unrelated state updates. What is wrong, and how do you fix it?
Show answer
The lazy call runs on every render of the layout, which creates a new component type each time. React treats it as a different component, unmounts the old one, and suspends again. Move the lazy call to module level, outside the component, so the component type stays the same across renders.
Exercise
Your app has a header with navigation links, and every route is lazy loaded. Where should you put the Suspense boundary so the header stays visible while a page chunk loads?
Show answer
Put it around the route outlet or the Routes element inside the layout, below the header. A Suspense placed above the whole layout would replace the header with the fallback during loading.