Lädt...


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


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

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.

...

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


📈 91.74 Punkte
🔧 Programmierung

🔧 How to Minimize React Bundle Size for Faster Loading Times


📈 39.8 Punkte
🔧 Programmierung

🔧 Tìm Hiểu Về RAG: Công Nghệ Đột Phá Đang "Làm Mưa Làm Gió" Trong Thế Giới Chatbot


📈 39.48 Punkte
🔧 Programmierung

🔧 The 5 Practical Uses of Lazy Loading in React


📈 35.47 Punkte
🔧 Programmierung

🔧 Top 5 React Lazy-Loading Images Libraries for 2023


📈 35.47 Punkte
🔧 Programmierung

🔧 A Guide on React Lazy Loading


📈 35.47 Punkte
🔧 Programmierung

🔧 Supercharging React Performance with TypeScript: Code Splitting and Lazy Loading 🚀


📈 35.47 Punkte
🔧 Programmierung

🔧 Supercharging React Performance with TypeScript: Code Splitting and Lazy Loading 🚀


📈 35.47 Punkte
🔧 Programmierung

🔧 Optimizing React Performance with Memoization and Lazy Loading


📈 35.47 Punkte
🔧 Programmierung

🔧 Optimizing React Performance with Memoization and Lazy Loading


📈 35.47 Punkte
🔧 Programmierung

🔧 Speed Up Your React App: A Guide to Lazy Loading 🚀


📈 35.47 Punkte
🔧 Programmierung

🔧 Implementando Lazy Loading em Componentes React


📈 35.47 Punkte
🔧 Programmierung

🔧 Speed Up Your React App: A Guide to Lazy Loading 🚀


📈 35.47 Punkte
🔧 Programmierung

🔧 Optimizing User Experience: The Lazy Loading Approach in React"


📈 35.47 Punkte
🔧 Programmierung

🔧 Lazy Loading Components In React


📈 35.47 Punkte
🔧 Programmierung

🔧 Nextjs | Parallel routes VS Intercepting routes


📈 34.87 Punkte
🔧 Programmierung

🔧 Implementing Photo Modal in Next JS using Parallel Routes & Intercepting Routes


📈 34.87 Punkte
🔧 Programmierung

🔧 Laravel Wildcard Routes & Fallback Routes


📈 34.87 Punkte
🔧 Programmierung

🔧 Made typos in routes? Redirect routes with functions


📈 34.87 Punkte
🔧 Programmierung

🔧 Next.js 14 Intercepting Routes with Dynamic Routes


📈 34.87 Punkte
🔧 Programmierung

🔧 Use React.lazy with confidence: A safe way to load components when iterating fast


📈 34.75 Punkte
🔧 Programmierung

🔧 Control Lazy Load, Infinite Scroll and Animations in React


📈 34.75 Punkte
🔧 Programmierung

🔧 How to Optimize Your Website for Faster Loading Times


📈 32.69 Punkte
🔧 Programmierung

🔧 Mastering Code Splitting: Unlocking Faster Load Times for Your JavaScript Applications


📈 31.96 Punkte
🔧 Programmierung

🔧 Optimizing WordPress for Faster Load Times and Improved Core Web Vitals


📈 31.96 Punkte
🔧 Programmierung

🔧 How to Implement Deferrable Views in Angular 17 for Faster Load Times


📈 31.96 Punkte
🔧 Programmierung

🔧 How to Implement Deferrable Views in Angular 17 for Faster Load Times


📈 31.96 Punkte
🔧 Programmierung

🔧 How to Implement Deferrable Views in Angular 17 for Faster Load Times


📈 31.96 Punkte
🔧 Programmierung

🔧 Tips and Tricks for Optimizing Magento 2 for Better Performance and Faster Load Times


📈 31.96 Punkte
🔧 Programmierung

📰 Mozilla, Cloudflare, Facebook and Others Propose BinaryAST For Faster JavaScript Load Times


📈 31.96 Punkte
📰 IT Security Nachrichten

📰 Mozilla Firefox 59 Released with Faster Page Load Times, New Privacy Features


📈 31.96 Punkte
📰 IT Security Nachrichten

📰 Mozilla Firefox 59 Released with Faster Page Load Times, New Privacy Features


📈 31.96 Punkte
📰 IT Security Nachrichten

📰 Chrome 52 for Android Arrives With Smoother Video Playback, Faster Load Times, and Better Battery Life


📈 31.96 Punkte
📰 IT Security

📰 Chrome 52 for Android Arrives With Smoother Video Playback, Faster Load Times, and Better Battery Life


📈 31.96 Punkte
📰 IT Security

🔧 Оптимизация React приложения с помощью React.lazy


📈 30.28 Punkte
🔧 Programmierung

matomo