React Lazy Load Routing with Lazy & Suspense Tutorial

In this post, we will learn how to build routes that lazy loads components in React js app, to create lazy load components we will use React lazy(), suspense component and react router dom version 6 module.

You must have heard the term React lazy before, but do you know what does it means?

Well, in this comprehensive guide, we will not just explain what React lazy is but also learn how to integrate react lazy in React to create the lazy loading router using react-router-dom version 6 library.

React library offers a lazy() function it ideally allows web developers to refrain UI from rendering unless it meets with a pre-defined condition. For instance, you have a specific component you don’t want to render in the view unless you receive a response from the server.

On the other hand, React offers a suspense component. The React suspense component is used to render the lazy load components inside its realm. It offers fallback content while the lazy component is being loaded.

How to Lazy Load Components with React Routes

  • Step 1: Download React Project
  • Step 2: Add Router DOM Library
  • Step 3: Build New Components
  • Step 4: Set Up BrowserRouter API
  • Step 5: Create Lazy Load Routes
  • Step 6: Start Development Server

Download React Project

You need to meet with certain conditions before you start development in React. You must have node, npm and create react app tools set up and configured in your development machine.

npm install create-react-app --global

After you full-filled given above conditions, your are ready to invoke the app installation process.

npx create-react-app react-blog

App is crated, so get into the app folder.

cd react-blog

Add Router DOM Library

The react router dom does not come included in react basic project, rather it needs to be added later to react project.

You can evoke the suggested command from the terminal screen.

npm install react-router-dom@6

Build New Components

You have to create the particular folder, make sure to name it components/:

Now, we will be creating new component files inside the components folder.

Create the new file name it Dashboard.js and add the given code inside of it:

import React from 'react'

function Dashboard() {
  return (
    <div>Dashboard</div>
  )
}

export default Dashboard

Build another file, name it Blog.js and add the given code inside of it:

import React from 'react'

function Blog() {
  return (
    <div>Blog</div>
  )
}

export default Blog

Next, make another file, name it BrokenPage.js and place the suggested code inside of it:

import React from 'react'

function BrokenPage() {
  return <div>This page does not exixst: 404 Error</div>
}

export default BrokenPage

Set Up BrowserRouter API

To set up the routing we need to wrap the global component with the help of the BrowserRouter module.

Hence, make sure to go to src/index.js file and copy the given code within the file.

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>,
)

Create Lazy Load Routes

We are now implement the lazy load components, you have to go to the App.js file. For setting up lazy loading in react, we will be adding or importing the components along with React lazy method and React suspense component.

import * as React from 'react'
import 'bootstrap/dist/css/bootstrap.min.css'
import { Routes, NavLink, Route } from 'react-router-dom'

import BrokenPage from './components/BrokenPage'

const Dashboard = React.lazy(() => import('./components/Dashboard'))
const Blog = React.lazy(() => import('./components/Blog'))

const App = () => {
  return (
    <div className="container mt-5">
      <h2>Lazy Loading Routes in React</h2>

      <p>
        <NavLink to="/">Dashboard</NavLink>
      </p>
      <p>
        <NavLink to="/blog">Blog</NavLink>
      </p>

      <Routes>
        <Route
          index
          element={
            <React.Suspense fallback={<>...</>}>
              <Dashboard />
            </React.Suspense>
          }
        />
        <Route
          path="blog"
          element={
            <React.Suspense fallback={<>...</>}>
              <Blog />
            </React.Suspense>
          }
        />
        <Route path="*" element={<BrokenPage />} />
      </Routes>
    </div>
  )
}

export default App

Start Development Server

We are going to initialize the react development server using provided command.

npm start

To test the small feature you have to open the app using the suggested url:

http://localhost:3000

React Create Lazy Load Router with Router DOM v6 Tutorial

Summary

The lazy loading technique primarily helps optimize web apps; it mainly renders only the required UI element. First, it gradually renders the non-essential elements later.

This lazy loading is required in react when the application size grows exponentially; it becomes tedious and cumbersome when the app’s size is extended.

In this tutorial, we have found out how to lazy load the components using the react routers. We have learned how to set up lazy load routes using the React lazy and React suspense components.