ReactMedium
What are lazy routes?
Lazy routes load a route's code only when the route is first visited, so the initial bundle contains just the code for the current page. In React Router data mode you give a route a lazy property that dynamically imports its component, loader and other exports; in declarative mode you wrap route components in React.lazy and <Suspense>. Frameworks (React Router framework mode, Next.js) split routes automatically.
React Router data mode: lazy
{ path: "reports", lazy: () => import("./routes/reports") }: the module exportsComponent,loader,action,ErrorBoundaryand so on.- The router loads the module when navigation to that route starts, then runs its loader, so code and data load without a render waterfall.
- Newer versions also accept an object form where each property (
Component,loader) can be loaded separately, allowing the loader to start before the component code arrives.
Declarative mode
const Reports = lazy(() => import("./pages/reports")) and <Route path="reports" element={<Suspense fallback={<Spinner />}><Reports /></Suspense>} />.
Benefits
- Smaller initial JavaScript, faster first load.
- Rarely used areas (admin, settings) cost nothing until visited.
Tips
- Prefetch likely routes:
<Link prefetch="intent">in framework mode, or call the import on hover. - Handle chunk load errors after deployments with an error boundary that offers a reload.
- Do not lazy-load the landing page or tiny routes; it only adds a request.
Code example
tsx
1import { lazy, Suspense } from "react";2import { createBrowserRouter } from "react-router";3import { BrowserRouter, Routes, Route } from "react-router";45// Data mode: the whole route module is loaded on first navigation6export const router = createBrowserRouter([7 { path: "/", Component: () => <h1>Home</h1> },8 { path: "/reports", lazy: () => import("./routes/reports") },9 // ./routes/reports.tsx exports: Component, loader, ErrorBoundary10]);1112// Declarative mode: React.lazy + Suspense per route13const Settings = lazy(() => import("./pages/settings"));1415export function DeclarativeApp() {16 return (17 <BrowserRouter>18 <Routes>19 <Route path="/" element={<h1>Home</h1>} />20 <Route21 path="/settings"22 element={23 <Suspense fallback={<p>Loading settings…</p>}>24 <Settings />25 </Suspense>26 }27 />28 </Routes>29 </BrowserRouter>30 );31}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.