React Lazy Loading: A Guide with Example

React Lazy Loading: A Guide with Example

Introduction

Lazy loading is a technique used to optimise the performance of React applications by loading components only when needed. This reduces the initial load time and improves the overall user experience. React provides built-in support for lazy loading through React.lazy() and Suspense.

What is Lazy Loading?

Lazy loading is a technique used in web development to delay loading non-essential resources (such as images, components, or scripts) until needed. In React, lazy loading is primarily used to improve performance by dynamically importing components only when required, instead of including them in the initial bundle.

React provides built-in support for lazy loading using React.lazy() and Suspense, allowing developers to load components asynchronously.

 

Why Use Lazy Loading?

  1. Improves Performance: Reduces the initial bundle size by loading components on demand.
  2. Faster Initial Load: Loads only the necessary components, making the application load faster.
  3. Optimised Resource Utilization: Loads heavy components only when required, saving bandwidth.

Implementing Lazy Loading in React

Let's see how to implement lazy loading with an example.

I’m going to create a new project 

Create a React Application

To create a new React app, you can use the create-react-app command-line tool, an officially supported way to create React applications. Here are the steps.

  1. Open your terminal or command prompt.
  2. Run the following command to install create-react-app globally (if you haven't done so before. 
    npm install -g create-react-app
    JavaScript

     

  3. -g This option stands for "global." When you install a package globally, it is installed in a central location on your computer and can be accessed from any directory.
  4. Once the installation is complete, create a new React app by running.
npx create-react-app lazy-loading-app
JavaScript

Move to the project folder and open the source in VS Code.

Image-01: Open the source in VS Code.

 

Step 1: Create Components

 

Now I'm going to create components. Go to the 'src' folder, right-click on it, and create a new folder named 'components'.

 

Create three simple components: Home.jsx,  About.jsx, and Contact.jsx.

Home.jsx

import React from "react";
import "./style.css";
export default function Home() {
  return (
    <div className="page-container">
      <h1>Welcome Home</h1>
    </div>
  );
}
JavaScript

About.jsx

import React from "react";
import "./style.css";
export default function About() {
  return (
    <div className="page-container">
      <h1>About Us</h1>
    </div>
  );
}
JavaScript

Contact.jsx

import React from "react";
import "./style.css";
export default function Contact() {
  return (
    <div className="page-container">
      <h1>Contact Us</h1>
    </div>
  );
}
JavaScript

Here, add a small CSS part also style.css

.page-container {
    font-size: 24px;
    color: #333;
    text-align: center;
    margin-top: 50px;
  }
CSS

APP.js

import React from "react";
import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
import "./App.css";
import Home from "./components/Home";
import About from "./components/About";
import Contact from "./components/Contact";


function App() {
  return (
    <Router>
      <div className="App">
        <header className="App-header">
          <nav className="navbar">
            <Link to="/">Home</Link> |{" "}
            <Link to="/about">About</Link> |{" "}
            <Link to="/contact">Contact</Link>
          </nav>
        </header>
        <main>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
          </Routes>
        </main>
      </div>
    </Router>
  );
}


export default App;
JavaScript

This code defines a React app with routing using react-router-dom. The Router component wraps the app and enables navigation between pages. Inside the header, Link components allow users to navigate between "Home," "About," and "Contact" pages. The Routes component maps the URLs to their corresponding components (Home, About, Contact) without reloading the page.

Add Css

.App-header {
  background-color: #282c34;
  min-height: 10vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start; /* Align content to top */
  padding-top: 40px; /* Add some space at the top */
  font-size: calc(10px + 2vmin);
  color: white;
}

/* New navbar styles */
.navbar {
  display: flex;
  gap: 20px;
  background-color: rgba(255, 255, 255, 0.1); /* slight contrast background */
  padding: 10px 20px;
  border-radius: 10px;
}

.navbar a {
  color: #61dafb;
  text-decoration: none;
  font-weight: bold;
}

.navbar a:hover {
  text-decoration: underline;
}


.App-link {
  color: #61dafb;
}
JavaScript

 

Now I’m going to run this app using ‘npm start’

Image 02: Run the app.

Image-03: View the app in browser mode.


 

 A JavaScript file is generated by a build tool like Webpack when you create or build a React app (or other JavaScript applications). It bundles all of your JavaScript, including your React components and dependencies, into a single or a few optimized files that can be loaded by the browser.

 

Purpose: It contains all the compiled JavaScript code from your source files (components, libraries, etc.). It bundles the code into a format that's efficient for the browser to load and execute. It makes the app's code easier to deploy since it's in a single file (or a few files).

How it works: When you run npm start or npm build, Webpack (or another bundler) takes all your JavaScript code, processes it, and combines everything into bundle.js. This file is then served by your local server (localhost:3000 in this case) when you visit the app in the browser.

Image-04: Here see the bundle.js size is 1.7 MB.

There are some potential disadvantages to consider when it comes to loading and managing this file

 

01 Large Initial Bundle Size: If you don't use code splitting or lazy loading properly, bundle.js can become very large, containing the entire application’s code, including all components and libraries

02 Inefficient Lazy Loading: If lazy loading is not set up optimally, users might have to wait for additional JavaScript chunks to be loaded when navigating between pages or interacting with certain parts of the app

03 Caching Issues: Since bundle.js is a large file, caching it for performance improvements is common. However, if you make any changes to the app, the cache might become outdated.

04 JavaScript Parsing and Execution Time: As bundle.js grows larger, the browser needs to parse and execute more JavaScript, which can increase the amount of time the browser spends on this task.

The disadvantages of bundle.js can be mitigated by using the lazy loading method. While bundle.js can significantly improve the performance of your app, especially with lazy loading, it can also cause issues if not managed properly.

Step 2: Implement Lazy Loading in App.js

Now, let's use React.lazy() to load these components only when needed.

App.js

import React, { Suspense, lazy } from "react";
import { BrowserRouter as Router, Route, Routes, Link } from "react-router-dom";
import "./App.css";


// Lazy-loaded components
const Home = lazy(() => import("./components/Home"));
const About = lazy(() => import("./components/About"));
const Contact = lazy(() => import("./components/Contact"));


// Fallback UI while loading
const Loading = () => <div>lazy Loading...</div>;


function App() {
  return (
    <Router>
      <div className="App">
        <header className="App-header">
          <nav className="navbar">
            <Link to="/">Home</Link>|
            <Link to="/about">About</Link>|
            <Link to="/contact">Contact</Link>
          </nav>
        </header>
        <main>
          <Suspense fallback={<Loading />}>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
              <Route path="/contact" element={<Contact />} />
            </Routes>
          </Suspense>
        </main>
      </div>
    </Router>
  );
}


export default App;
JavaScript

This code demonstrates the use of React's lazy loading and Suspense for code splitting, allowing components to load only when needed, which improves the initial load time of the app.

Lazy-loaded components: The lazy() function is used to dynamically import the Home, About, and Contact components. This means that these components won’t be loaded initially with the app; they will be fetched only when the user navigates to their respective routes.

// Lazy-loaded components
const Home = lazy(() => import("./components/Home"));
const About = lazy(() => import("./components/About"));
const Contact = lazy(() => import("./components/Contact"));
JavaScript

Fallback UI while loading: The Loading component is a simple placeholder that is displayed while any of the lazy-loaded components are being fetched. It's a UI indicator to inform the user that the content is loading.

// Fallback UI while loading
const Loading = () => <div>lazy Loading...</div>;
JavaScript

App component:

  • The Router wraps the entire application, enabling navigation between different pages.
  • The nav bar contains Link components that let users navigate to the Home, About, and Contact pages.
  • Inside the main section, Suspense is used to wrap the routes. This is where the lazy-loaded components are rendered. The fallback prop ensures that the Loading component is shown while the actual components are loading.

Image-05: Implementing the lazy loading.

Image-06 

Advantages of Lazy Loading

 Improves Performance & Speed

  • Reduces the initial page load time by loading only essential components first.
  • Helps in optimizing the application for a better user experience.

 Reduces Bundle Size

  • Since components are loaded on demand, the overall JavaScript bundle size remains small.
  • This is particularly useful for large applications with many components.

 Better Resource Utilization

  • Prevents unnecessary resource consumption by loading components only when required.
  • Saves bandwidth for users with slow internet connections.

 Enhances User Experience

  • Users can start interacting with the website without waiting for all components to load at once.

Conclusion

Lazy loading in React is an effective way to optimize performance by loading components only when required. By using React.lazy() and Suspense, we can improve the efficiency of our applications and provide a better user experience.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up Next
    Ebook Download
    View all
    Learn
    View all
    Globally based Software Developing & Data Processing Company