How to Lazy Load Components in React Routing

In this React js tutorial, we will discuss, how to implement lazy loading in react routing using the React Router DOM library package. Large-scale complex applications have a huge number of components, which can increase the initialization time of an application, as all of the components start loading at the same time. Moreover, each component…

By.

•

min read

In this React js tutorial, we will discuss, how to implement lazy loading in react routing using the React Router DOM library package.

Large-scale complex applications have a huge number of components, which can increase the initialization time of an application, as all of the components start loading at the same time. Moreover, each component may have heavy assets like images or other media to add up to the loading chaos.

Lazy loading is a technique used in various JavaScript-based applications to enhance the optimization of applications. In such architecture, the lazy-loaded components are rendered only on demand when a user navigates to its related path.

We can easily implement the lazy loaded routing in React application using the React Router DOM library.

How to Lazy Load Components in React Application?

Step 1 – Create React App

Step 2 – Installation of React Router DOM

Step 3 – Create Components

Step 4 – Define Lazy Loaded Routes

Step 5 – See In Action

 

Step 1 – Create React App

In your development system, the create react app tool need to be installed before creating the React application. Execute below command for installation:

npm install create-react-app --global

 

Thereafter, you can execute below command to create a new React application with provided name:

npx create-react-app react--route-app

 

Move into the application directory by executing the below command in the terminal:

cd react--route-app

 

Step 2 – Installation of React Router DOM

For the implementation of Routing in react app, install the React Router DOM package at the project root:

npm install react-router-dom

 

Step 3 – Create Components

Next, to test lazy loading on Component, we will create the following components. In the src folder at the application root, create components folder.

Create src/components/Dashboard.tsx file with following content:

import * as React from 'react';
function Dashboard() {
  return <div>Dashboard Page</div>;
}
export default Dashboard;

 

Create src/components/Details.tsx file:

import * as React from 'react';
function Details() {
  return <div>Details Page</div>;
}
export default Details;

 

Create src/components/NotFound.tsx to display a message if the user enter wrong path:

import * as React from 'react';
function NotFound() {
  return <div>Page Not Found!</div>;
}
export default NotFound;

 

Step 4 – Define Lazy Loaded Routes

React Router DOM helps to define lazy loaded routing by using the <React.Suspense> component. It limits the auto loading of Components defined and only loads when demanded or a specific condition is met.

It also provides a fallback option, which can take a String or another component.

Open the App.js file and place the Routing definition as shown below:

import * as React from 'react';
import './style.css';
import { Routes, Route, NavLink, BrowserRouter } from 'react-router-dom';
import NotFound from './components/NotFound';
import Dashboard from './components/Dashboard';
const Details = React.lazy(() => import('./components/Details'));
const App = () => {
  return (
    <div>
      <BrowserRouter>
        <nav>
          <NavLink to="/">Dashboard</NavLink>
          <NavLink to="/details">Details</NavLink>
        </nav>
        <Routes>
          <Route
            index
            element={
              <React.Suspense fallback={<>...</>}>
                <Dashboard />
              </React.Suspense>
            }
          />
          <Route
            path="details"
            element={
              <React.Suspense fallback={<>...</>}>
                <Details />
              </React.Suspense>
            }
          />
          <Route path="*" element={<NotFound />} />
        </Routes>
      </BrowserRouter>
    </div>
  );
};
export default App;

 

Step 5 – See In Action

Now you can run your react application in the development server. Run following command to start your application:

npm start

It will start your application at following URL:

http://localhost:3000/

 

Conclusion

In this guide, we discussed a very important topic on adding lazy loading routes in React applications using react-router DOM library. Lazy loading helps in optimising the performance of large Javascript applications like React.

Leave a Reply

Your email address will not be published. Required fields are marked *