7

Lazy Loading Routes in React: The Key to Faster Load Times

 1 year ago
source link: https://dev.to/franciscomendes10866/lazy-loading-routes-in-react-the-key-to-faster-load-times-15bi
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Introduction

Lazy loading is a technique used to improve the performance of web applications by loading only the necessary resources when they are needed. In React applications, lazy loading can be implemented using React Router DOM to load routes asynchronously, thus improving the initial loading time of the application.

React Router DOM is a popular library used for routing in React applications. It allows developers to define routes and their associated components that should be rendered when a specific URL is requested. By default, React Router DOM loads all the routes and their associated components when the application is loaded, which can result in a slower loading time for larger applications.

To overcome this issue, React provides a feature called lazy, which allows developers to load components only when they are needed. In this article, we will discuss how to implement lazy loading of routes in a React app.

Step 1: Dependencies

The first step is to install React Router DOM using NPM or Yarn. You can install it by running the following command:

npm install react-router-dom

Step 2: Create a Lazy Component

To implement lazy loading of a route, we need to create a lazy component that will load the required component only when it is needed. React provides a built-in function called lazy() that can be used to create lazy components.

For example, let's say we have a component called Dashboard that we want to lazy load:

// @/pages/Dashboard.jsx
import React from "react";

// named export component
export const Dashboard = () => {
  return <h1>Dashboard</h1>;
}

// default export component
export default function Dashboard() {
  return <h1>Dashboard</h1>;
}

We can create a lazy component for it as follows:

// @/router/loaders.js
import { lazy } from 'react';

// load named export component
export const LazyDashboard = lazy(
  () => import('../pages/Dashboard')
    .then((module) => ({ default: module.Dashboard }))
);

// load default export component
export const LazyDashboard = lazy(
  () => import('../pages/Dashboard')
);

The lazy() function takes a function that returns a dynamic import() statement that loads the required component. The import() statement returns a promise that resolves to the required component.

Step 3: Define a Lazy Route

Once we have created the lazy component, we can define a lazy route using React Router DOM. A lazy route is defined in the same way as a regular route, except that we use the lazy() function to load the component asynchronously.

For example, let's say we want to lazy load the Dashboard component when the user navigates to the /dashboard URL. We can define the lazy route as follows:

// @/router/index.jsx
import { BrowserRouter, Routes, Route } from 'react-router-dom';

import { LazyDashboard } from "./loaders";

export function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route
          exact
          path="/dashboard"
          element={<LazyDashboard />}
        />
      </Routes>
    </BrowserRouter>
  )
}

In the above example, we use the exact prop to ensure that the route matches only when the URL exactly matches /dashboard. We pass the lazy component LazyDashboard as the component prop.

Step 4: Wrap the App with Suspense

When the lazy component is loading, React will render a fallback component until the component is loaded. We can define a loading component to display a loading indicator to the user.

Finally, we need to wrap the entire application with a Suspense component to ensure that the loading component is displayed when the lazy component is being loaded.

For example, we can wrap the App component with the Suspense component as follows:

// @/router/index.jsx
import { Suspense } from "react";
import { BrowserRouter, Routes, Route } from 'react-router-dom';

import { LazyDashboard } from "./loaders";

export function App() {
  return (
    <Suspense fallback={<h3>Loading...</h3>}>
      <BrowserRouter>
        <Routes>
          <Route
            exact
            path="/dashboard"
            element={<LazyDashboard />}
          />
        </Routes>
      </BrowserRouter>
    </Suspense>
  )
}

In the above example, we use the Suspense component to wrap the BrowserRouter component that contains all the routes of the application. We pass the "Loading..." text (element) as the fallback prop, which will be displayed until the lazy component is loaded.

Recap

Lazy loading of routes is an effective technique to improve the performance of React applications. React Router DOM provides built-in support for lazy loading of routes, which can be easily implemented using the lazy() function and the Suspense component.

By using lazy loading, we can reduce the initial loading time of the application and improve the user experience. However, it is important to use lazy loading judiciously and only for larger components that are not required immediately, as lazy loading can also have a negative impact on the user experience if used excessively.

Conclusion

I hope you found this article helpful, whether you're using the information in an existing project or just giving it a try for fun. Please let me know if you notice any mistakes in the article by leaving a comment.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK