What is Lazy Loading in React?

This article explains the concept of lazy loading in React, a performance optimization technique that delays the loading of non-critical resources. You will discover how lazy loading works, why it is essential for modern web applications, and how to implement it using React’s built-in React.lazy and Suspense features.

Understanding Lazy Loading

By default, when a React application builds, bundling tools like Webpack pack the entire application code into a single, large JavaScript file. This means a user must download the complete application before they can see or interact with the first page.

Lazy loading solves this problem by splitting the application code into smaller chunks. Instead of loading everything upfront, React only loads specific components or pages when the user actually needs them.

Key Benefits of Lazy Loading

How to Implement Lazy Loading in React

React provides two built-in features to make lazy loading simple: React.lazy() and the Suspense component.

  1. React.lazy(): This function allows you to render a dynamic import as a regular component.
  2. Suspense: This component wraps your lazy-loaded components. It accepts a fallback prop, which displays temporary UI (like a loading spinner or text) while the lazy component is loading in the background.

Code Example

Here is a basic implementation of lazy loading a component in React:

import React, { Suspense } from 'react';

// Lazy load the component
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));

function App() {
  return (
    <div>
      <h1>Welcome to My App</h1>
      
      {/* Wrap the lazy component in Suspense */}
      <Suspense fallback={<div>Loading component...</div>}>
        <HeavyComponent />
      </Suspense>
    </div>
  );
}

export default App;

In this example, HeavyComponent will not be loaded into the user’s browser until the App component renders. While the browser fetches the file for HeavyComponent, the user will see the message “Loading component…”.

Best Practices for Lazy Loading