Lazy Loading in ReactJS


In this article, we will learn how to lazily load the pages of our application to make our React application more optimized.

React apps are bundled with the preinstalled bundlers like webpack before making the React application to be production ready. When this bundled project is loaded, it loads the whole source code at once, even those pages which are rarely visited by the user. So, to prevent the entire loading of the application at once, we use the concept of lazy loading to decrease the DOM load time and to increase the speed of the application.

Syntax

const OtherComponent = React.lazy(() => import('./OtherComponent'));

Here, OtherComponent is the component which is going to be lazily loaded.

Example

In this example, we will build a Routing application which lazily loads the component.

App.jsx

import React, { Suspense, lazy } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react -router-dom';

const About = lazy(() => import('./About'));

const App = () => (
   <Router>
   <Suspense fallback={<div>Loading...</div>}>
   <Switch>
   <Route path="/about" component={About} />
   <Route
      path="/"
      exact
      render={() => (
      <div>
         <h1>This is the main page</h1>
         <a href="/about">Click here</a>
      </div>
      )}
   />
   </Switch>
   </Suspense>
   </Router>
);
export default App;

About.js

import React from 'react';

const About = () => {
   return (
      <div>
         <h1>This is the about section</h1>
      </div>
   );
};
export default About;

In the above example, when the user clicks on the 'click here' button. the about.js script is lazily loaded and the DOM is updated accordingly.

Output

This will produce the following result.

Updated on: 18-Mar-2021

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements