Skip to content
Shubham JangleResources
React

Explore topics

React Lazy Loading & Suspense: Part 1

Watch the walkthrough
Open on Instagram

Quick revision

Code splitting reduces the JavaScript needed for the first screen. lazy(() => import(...)) defers loading a component module until React first tries to render it. Declare lazy components at module scope and make sure the imported module has the expected default export.

Suspense displays a fallback while a descendant suspends. It does not make synchronous CPU work run on another thread, and it does not catch an import failure; use an Error Boundary for failures. Group boundaries around meaningful loading regions and reserve layout space for the fallback.

Read the copied example

App.tsx is the checkout's later viewport-triggered version, rather than a separate Part 1 snapshot. It imports Suspense but does not render a Suspense boundary. IntersectionSuspense controls when children mount and supplies a pre-visibility placeholder, but it does not itself handle a pending lazy import.

Original revision pattern, to place around a lazy child:

<Suspense fallback={<p>Loading component...</p>}>
  <HeavyComponent />
</Suspense>

Compare the expensive render in HeavyComponent.tsx with the worker lesson. Measure downloaded chunks and main-thread time separately. LightComponent's local button and utility dependencies are also copied below.

References: React lazy and Suspense boundaries.

Original repository source

These are the supplied checkout's React 18/Vite examples. Code is preserved apart from line endings; revision recommendations above are separate. Use the original project dependencies and configuration when running them.

App.tsx

Original file on GitHub

import { lazy, Suspense } from "react";

import LightComponent from "./LightComponent";
import IntersectionSuspense from "./IntersectionSuspense";
// import IntersectionSuspense from "./IntersectionSuspense";

/* Normal Imports */
// import HeavyComponent from "./HeavyComponent";
// import HeavyComponent2 from "./HeavyComponent2";
// import HeavyComponent3 from "./HeavyComponent3";

/** Lazy Imports */
const HeavyComponent = lazy(() => import("./HeavyComponent"));
const HeavyComponent2 = lazy(() => import("./HeavyComponent2"));
const HeavyComponent3 = lazy(() => import("./HeavyComponent3"));

// Main Dashboard Component
const App2 = () => {
  return (
    <div className="container mx-auto p-6">
      <h1 className="text-2xl font-bold mb-6">React Lazy Loading</h1>
      <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <LightComponent />
        <LightComponent />
        <LightComponent />
        <LightComponent />
        <IntersectionSuspense
          fallback={
            <div className="h-64 bg-gray-200 animate-pulse p-2">
              Loading Heavy Component 1
            </div>
          }
        >
          <HeavyComponent />
        </IntersectionSuspense>
        <LightComponent />
        <LightComponent />
        <LightComponent />
        <IntersectionSuspense
          fallback={
            <div className="h-64 bg-gray-200 animate-pulse p-2">
              Loading Heavy Component 2
            </div>
          }
        >
          <HeavyComponent2 />
        </IntersectionSuspense>
        <LightComponent />
        <LightComponent />
        <LightComponent />
        <IntersectionSuspense
          fallback={
            <div className="h-64 bg-gray-200 animate-pulse p-2">
              Loading Heavy Component 3
            </div>
          }
        >
          <HeavyComponent3 />
        </IntersectionSuspense>
      </div>
    </div>
  );
};

export default App2;

IntersectionSuspense.tsx

Original file on GitHub

import React, { useState, useEffect } from "react";
import { useInView } from "react-intersection-observer";

interface IntersectionSuspenseProps {
  children: React.ReactNode;
  fallback: React.ReactNode;
  threshold?: number;
}

const IntersectionSuspense: React.FC<IntersectionSuspenseProps> = ({
  children,
  fallback,
  threshold = 0.1,
}) => {
  const [hasBeenLoaded, setHasBeenLoaded] = useState(false);
  const [ref, isInView] = useInView({ threshold });

  useEffect(() => {
    if (isInView && !hasBeenLoaded) {
      setHasBeenLoaded(true);
    }
  }, [isInView, hasBeenLoaded]);

  return <div ref={ref}>{hasBeenLoaded || isInView ? children : fallback}</div>;
};

export default IntersectionSuspense;

HeavyComponent.tsx

Original file on GitHub

const HeavyComponent = () => {
  const expensiveCalculation = () => {
    let result = 0;
    // for loop: 100 million times
    for (let i = 0; i < 100000000; i++) {
      result += Math.sin(i) * Math.cos(i);
    }
    return result;
  };

  const computationResult = expensiveCalculation();

  return (
    <div className="p-6 bg-orange-100 rounded-lg">
      <h2 className="text-2xl font-bold mb-4">Heavy Component 1</h2>
      <p className="text-sm text-gray-600 my-2">
        This component took significant time to render due to heavy
        computational work {computationResult}
      </p>
      <img className="rounded-md" src="her_1.png" alt="her_1" />
    </div>
  );
};
export default HeavyComponent;

HeavyComponent2.tsx

Original file on GitHub

import React, { useState, useEffect } from "react";

const HeavyComponent2 = () => {
  const [computationResult, setComputationResult] = useState<number | null>(
    null
  );

  useEffect(() => {
    const worker = new Worker(new URL("./worker.js", import.meta.url));

    worker.postMessage({ type: "expensiveCalculation" });

    worker.onmessage = (e) => {
      setComputationResult(e.data);
      worker.terminate();
    };

    return () => worker.terminate();
  }, []);

  return (
    <div className="p-6 bg-orange-100 rounded-lg">
      <h2 className="text-2xl font-bold mb-4">Heavy Component 2</h2>
      {computationResult === null ? (
        <p className="text-sm text-gray-600 my-2">Loading...</p>
      ) : (
        <>
          <p className="text-sm text-gray-600 my-2">
            This component took significant time to render due to heavy
            computational work. Computation Result: {computationResult}
          </p>
          <img className="rounded-md" src="her_1.png" alt="her_1" />
        </>
      )}
    </div>
  );
};

export default HeavyComponent2;

worker.js

Original file on GitHub

self.onmessage = (e) => {
  const { type, payload } = e.data;

  if (type === "expensiveCalculation") {
    let result = 0;
    for (let i = 0; i < 100000000; i++) {
      result += Math.sin(i) * Math.cos(i);
    }
    postMessage(result); // Send the result back to the main thread
  }
};

HeavyComponent3.tsx

Original file on GitHub

const HeavyComponent3 = () => {
  return (
    <div className="p-6 bg-orange-100 rounded-lg">
      <h2 className="text-2xl font-bold mb-4">Heavy Component</h2>
      <p className="text-sm text-gray-600 my-2">
        This component took significant time to render due to heavy
        computational work.
      </p>
      <img className="rounded-md" src="her_3.png" alt="her_3" />
    </div>
  );
};
export default HeavyComponent3;

LightComponent.tsx

Original file on GitHub

import { useState } from "react";
import { Button } from "./ui/button";

const LightComponent = () => {
  const [count, setCount] = useState(0);

  return (
    <div className="p-6 bg-blue-100 rounded-lg">
      <h2 className="text-2xl font-bold mb-4">Light Component</h2>
      <p>Counter Value: {count}</p>
      <p className="text-sm text-gray-600 mt-2 space-x-2">
        <Button className="bg-blue-800" onClick={() => setCount((c) => c + 1)}>
          +
        </Button>
        <Button className="bg-blue-800" onClick={() => setCount((c) => c - 1)}>
          -
        </Button>
      </p>
    </div>
  );
};
export default LightComponent;

button.tsx

Original file on GitHub

import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"

const buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default:
          "bg-primary text-primary-foreground shadow hover:bg-primary/90",
        destructive:
          "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
        outline:
          "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
        secondary:
          "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "h-9 w-9",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

export interface ButtonProps
  extends React.ButtonHTMLAttributes<HTMLButtonElement>,
    VariantProps<typeof buttonVariants> {
  asChild?: boolean
}

const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
  ({ className, variant, size, asChild = false, ...props }, ref) => {
    const Comp = asChild ? Slot : "button"
    return (
      <Comp
        className={cn(buttonVariants({ variant, size, className }))}
        ref={ref}
        {...props}
      />
    )
  }
)
Button.displayName = "Button"

export { Button, buttonVariants }

utils.ts

Original file on GitHub

import { clsx, type ClassValue } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs: ClassValue[]) {
  return twMerge(clsx(inputs))
}