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 {A, useRoute} from 'routescape';
import {Intro} from './Intro';
- import {Projects} from './Projects';
+ import {Projects} from './Projects.lazy';
export const App = () => {
let [, withRoute] = useRoute();
return (
<>
<nav>
<A href="/">Intro</A>
<A href="/projects">Projects</A>
</nav>
{withRoute('/', (
<Intro/>
))}
{withRoute('/projects', (
- <Projects/>
+ <Suspense fallback={<p>Loading...</p>}>
+ <Projects/>
+ </Suspense>
))}
</>
);
};
+ // Projects.lazy.js
+ import {lazy} from 'react';
+
+ export const Projects = lazy(() => import('./Projects'));
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>
.
← Unknown routes | GitHub ✦