D Dev Notebook

React Lazy Loading

Lazy Loading

What is lazy loading?

  • In React, this usually means loading a component only when it’s needed (like when the user navigates to a route), instead of loading everything when the app starts.
  • Don’t load something until you actually need it. This makes your app faster to load initially.

Why use lazy loading?

  • Smaller initial bundle (faster first load).
  • Loads components only when required.
  • Better performance, especially for large apps.

👉 Without lazy loading: All components load on the first visit = slower initial load.

👉 With lazy loading: Load only what you need, when you need it = faster initial load.

we don’t need to install anything extra for React lazy loading. It’s built into React (since React 16.6+).

Example : lazy loading images on scroll

import React from "react";

export default function App() {
  return (
    <div style={{ padding: "20px" }}>
      <h1>Lazy Loading 50 Images</h1>
      <p>Scroll down to load more images.</p>
      {[...Array(50)].map((_, i) => (
        <img
          key={i}
          src={`https://picsum.photos/id/${i + 10}/400/300`}
          alt={`Random ${i}`}
          loading="lazy"
          style={{
            display: "block",
            marginBottom: "20px",
            width: "400px",
            height: "300px",
            objectFit: "cover",
            borderRadius: "8px",
            boxShadow: "0 2px 8px rgba(0,0,0,0.2)"
          }}
        />
      ))}
    </div>
  );
}

How it works

  • Each <img> tag has loading="lazy" — this tells the browser.
  • Don’t load this image until it’s close to appearing in the viewport.
  • Modern browsers (Chrome, Firefox, Edge) support this natively.

On this page