T8 React Router

Lazy routes

Lazy routes are routes whose content is loaded on demand, when the route is visited.

Enabling lazy routes doesn't require a specific routing setup. It's a combination of the route matching and lazily loaded React components (with React.lazy() and React's <Suspense>), processed by a code-splitting-capable build tool (like Esbuild, Webpack, Rollup, Vite):

+ import { Suspense } from "react";
- import { Projects } from "./Projects";
+ import { Projects } from "./Projects.lazy";

  let App = () => (
    <>
      // ...
      {withRoute("/projects", (
-       <Projects/>
+       <Suspense fallback={<p>Loading...</p>}>
+         <Projects/>
+       </Suspense>
      ))}
    </>
  );
+ // Projects.lazy.ts
+ import { lazy } from "react";
+
+ export const Projects = lazy(() => import("./Projects"));

Lazy routes live demo

In this example, the <Projects> component isn't loaded until the corresponding /projects route is visited. When it's first visited, while the component is being fetched, <p>Loading...</p> shows up, as specified with the fallback prop of <Suspense>.