Lazy Loading Pattern

Overview

Lazy loading is a technique that defers loading of non-critical resources at page load time. Instead, these resources are loaded only when needed. In React, this is achieved throughReact.lazy() andSuspense which allow you to render a loading indicator while waiting for components to load.

Example

Click the button below to load a component that is imported with React.lazy(). You'll see a loading indicator while the component is being fetched.

Code Implementation

// In your page file (e.g., LazyLoadingPage.tsx)
import React, { useState, Suspense, lazy } from "react";

// Lazy load the component
const LazyComponent = lazy(() => import("@/components/LazyComponent"));

export default function LazyLoadingPage() {
  const [isComponentLoaded, setIsComponentLoaded] = useState(false);
  
  const loadComponent = () => {
    setIsComponentLoaded(true);
  };
  
  return (
    <div>
      {!isComponentLoaded ? (
        <button onClick={loadComponent}>
          Load Component
        </button>
      ) : (
        <Suspense fallback={<div>Loading...</div>}>
          <LazyComponent />
        </Suspense>
      )}
    </div>
  );
}

// LazyComponent.tsx
import React from "react";

const LazyComponent = () => {
  return (
    <div>
      <h2>Lazy Loaded Component</h2>
      <p>This component was loaded only when needed!</p>
      {/* Heavy component content goes here */}
    </div>
  );
};

export default LazyComponent;

Key Benefits

  • Reduced initial bundle size for faster page loads
  • Components are loaded only when they're actually needed
  • Better performance for large applications with many components
  • Code splitting across multiple smaller bundles
  • Improved user experience with loading indicators
  • Reduced memory usage by loading only what's necessary