Enable Dark Mode!
how-to-lazy-load-components-in-react.jpg
By: Alan Joy

How to Lazy Load Components in React

Technical React

For a large React application that contains many pages, components, images, and libraries. Loading everything at the start of the application can increase the initial bundle size and also make the application take longer to load. Lazy loading is a technique that can help improve the performance of React applications. It loads the components only when they are needed, instead of downloading all the code when the application starts. With this technique, React can load specific components only when users navigate to that page or open a particular section.

In this blog, we will learn how to implement the lazy loading feature for React components using the lazy() method provided by React.

1. What Is Lazy Loading in React?

Lazy loading means the technique of delaying the loading of a resource until it is actually required. In the case of a large application that has different pages like the dashboard, reports, settings, and users. There is no need to load all the codes for each page at the start; we can lazy load the page code only when a user visits that page. This helps reduce the initial JavaScript bundle size, avoid loading unused code, and improve the initial loading performance. React has two built-in features for this - lazy() and Suspense.

2. Create a React Project

We can create a new vite react application with this.

npm create vite@latest react-lazy-loading -- --template react
cd react-lazy-loading
npm install
npm run dev

3. Create a Component to Lazy Load

First, we can create a component named Dashboard.js inside the src folder. This is a normal React component that we will load with the lazy method.

export default function Dashboard() {
 return (
   <div>
     <h2>Dashboard</h2>
     <p>Welcome to your dashboard.</p>
   </div>
 );
}

4. Use React.lazy() to Load Components

Now, we can set up lazy loading. Normally, we will import components at the beginning of a file like this.

import Dashboard from "./Dashboard";

We need to update this line and handle the component importing using the lazy() method as shown below.

import { lazy } from "react";
const Dashboard = lazy(() => import("./Dashboard"));

5. Use Suspense to Handle Loading States

Now, React will lazy load the component, so the component needs to be downloaded whenever it is needed. When this component is being downloaded, react needs to display something. This is where we use the help of Suspense. Update our App.jsx with this.

import { lazy, Suspense } from "react";
const Dashboard = lazy(() => import("./Dashboard"));
export default function App() {
 return (
   <div>
     <h1>My Application</h1>
     <Suspense fallback={<p>Loading dashboard...</p>}>
       <Dashboard />
     </Suspense>
   </div>
 );
}

The Suspense component accepts a fallback value. This content will be displayed while the component is lazily loaded. When the component is loaded and ready, React automatically replaces the fallback with the actual component.

6. Lazy Load Multiple Components

We can lazy load multiple components in the same application. For example, we can create two additional components named Reports.jsx and Settings.jsx.

Reports.jsx

export default function Reports() {
 return <h2>Reports Page</h2>;
}

Settings.jsx

export default function Settings() {
 return <h2>Settings Page</h2>;
}

Now we can import them with lazy().

import { lazy, Suspense, useState } from "react";
const Dashboard = lazy(() => import("./Dashboard"));
const Reports = lazy(() => import("./Reports"));
const Settings = lazy(() => import("./Settings"));
export default function App() {
 const [page, setPage] = useState("dashboard");
 const pages = {
   dashboard: <Dashboard />,
   reports: <Reports />,
   settings: <Settings />,
 };
 return (
   <div>
     <nav className="flex gap-4">
       <button onClick={() => setPage("dashboard")}>
         Dashboard
       </button>
       <button onClick={() => setPage("reports")}>
         Reports
       </button>
       <button onClick={() => setPage("settings")}>
         Settings
       </button>
     </nav>
     <Suspense fallback={<p>Loading page...</p>}>
       {pages[page]}
     </Suspense>
   </div>
 );
}

Lazy loading is a simple way to improve the loading experience of react applications. Instead of loading every component immediately, we are splitting the application into smaller chunks and only loading them when they are required. One thing to keep in mind is that we should only lazy load the components that are not required immediately. Also, it is not a good idea to lazy load every small component. These things can introduce unnecessary loading delays and create additional network requests. Use it in components where it can provide meaningful performance benefits.

To read more about How to Create an Accordion Component in React, refer to our blog How to Create an Accordion Component in React.


Frequently Asked Questions

What is lazy loading in React?

Lazy loading is a technique that loads components only when they are needed, helping reduce the initial JavaScript bundle size.

What is the difference between React.lazy() and Suspense?

React.lazy() dynamically imports a component, while Suspense displays fallback content while that component is loading.

Can I use lazy loading with React Router?

Yes. You can use React.lazy() and Suspense to load route components only when users navigate to their respective pages.

If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



WhatsApp