Join the Nature Wishlist Discord to get help, share your projects, and discuss JavaScript.
⚡️ ⏐ Performance Patterns
5. Route-based Splitting

Route Based Splitting

Dynamically load components based on the current route


If your application has multiple pages, we can use dynamic imports to only load the resources that are needed for the current route. Instead of the code for all the possible pages in the initial bundle, we can bundle-split based on routes. This approach allows us to defer loading the bundle until the user actually navigates to that page.


If you're using react-router for navigation, you can wrap the Switch component in a React.Suspense, and import the routes using React.lazy. This automatically enables route-based code splitting.

import React, { lazy, Suspense } from "react";
import { Switch, Route, BrowserRouter as Router } from "react-router-dom";
const App = lazy(() => import("./App"));
const About = lazy(() => import("./About"));
const Contact = lazy(() => import("./Contact"));
    <Suspense fallback={<div>Loading...</div>}>
        <Route exact path="/">
          <App />
        <Route path="/about">
          <About />
        <Route path="/contact">
          <Contact />


Faster initial load: Dynamically importing the pages reduces the initial bundle size - allowing for a smaller initial load since the client doesn't have to download and execute as much, saving bandwidth.