React Lazy Loading Router using React Router DOM v6 Tutorial

Last updated on: by Digamber

Lazy loading is a technique that enables us to load a specific component when a particular route is accessed. It exponentially enhances the load time and the loading speed. At the same time, it increases the react application performance.

In this React router DOM tutorial, we will show you how to create lazy load routes in React js application using the React Router DOM version 6 library.

To increase the performance, we will follow the code splitting technique, so when the user navigates within the app, only the specific routes will load.

To implement the lazy loading in React router, we will use the function component and React router dom APIs, such as Routes, Route and Link.

How to Implement Lazy Loading in React Routers with Router DOM Library

  • Step 1: Create React App
  • Step 2: Install React Router DOM Module
  • Step 3: Create Component Files
  • Step 4: Add Browser Router in React
  • Step 5: Add Lazy Loading in Routes
  • Step 6: View App on Browser

Create React App

The create-react-app tool has to be installed in your development system, if it is not then execute the give command:

npm install create-react-app --global

As soon as the given above tools is added, make sure to install a new react app:

npx create-react-app react-demo

Get inside the project folder after the app is created:

cd react-demo

Install React Router DOM Module

Here is the command that will invoke the installation of React Router DOM version 6 in React project:

npm install react-router-dom@6

Create Component Files

To create the lazy load routes, we need to create couple of components:

Create components/ folder and also make the Home.js file:

import React from 'react'
function Home() {
  return (
    <div>Home</div>
  )
}
export default Home

In the components/ folder create the Product.js file:

import React from 'react'
function Product() {
  return (
    <div>Product</div>
  )
}
export default Product

In the components/ folder create the NoPage.js file:

import React from 'react'
function NoPage() {
  return <div>You've landed on a wrong planet: 404</div>
}
export default NoPage

Add Browser Router in React

Head over to src/ folder, open the index.js file then import the BrowserRouter api, and wrap the App component with BrowserRouter api.

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { BrowserRouter } from 'react-router-dom'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
)

BrowserRouter is the recommended interface for running React Router in a web browser. A BrowserRouter stores the current location in the browser’s address bar using clean URLs and navigates using the browser’s built-in history stack.

Add Lazy Loading in Routes

React Suspense is a React component that stops a component from being rendered unless a specific condition is met. It shows a fallback option, and it could be a string or another React component.

Open App.js file and place the given code into the file.

import * as React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import { Routes, Route, NavLink } from 'react-router-dom'
import NoPage from './components/NoPage'
const Home = React.lazy(() => import('./components/Home'))
const Product = React.lazy(() => import('./components/Product'))
const App = () => {
  return (
    <div className="container mt-5">
      <h2 className="mb-3">React Lazy Loading Routes Example</h2>
      <nav>
        <NavLink to="/">Home</NavLink>
        <NavLink to="/product">Product</NavLink>
      </nav>
      <Routes>
        <Route
          index
          element={
            <React.Suspense fallback={<>...</>}>
              <Home />
            </React.Suspense>
          }
        />
        <Route
          path="product"
          element={
            <React.Suspense fallback={<>...</>}>
              <Product />
            </React.Suspense>
          }
        />
        <Route path="*" element={<NoPage />} />
      </Routes>
    </div>
  )
}
export default App

View App on Browser

We have to run the react development server using the following command:

npm start

You can checkout the given app using the following url:

http://localhost:3000

React Lazy Loading Router using React Router DOM v6 Tutorial

Conclusion

In this tutorial, we elaborate on the working process of Route Lazy loading in React js application. We learned how to use the lazy loading function to lazy load the routes and simultaneously improve the performance of React app.

Digamber

I am Digamber, a full-stack developer and fitness aficionado. I created this site to bestow my coding experience with newbie programmers. I love to write on JavaScript, ECMAScript, React, Angular, Vue, Laravel.