Skip to main content

Command Palette

Search for a command to run...

29) React.lazy and Suspense

Updated
View as Markdown
  1. What is React.lazy
    React.lazy is a feature in React that enables code splitting at the component level—it lets you load components only when they’re needed instead of bundling everything upfront.
    “Load a component on demand (lazy loading) rather than at initial page load.” This reduces your initial bundle size and speeds up app startup.
    React.lazy enables code splitting by loading components dynamically when they are needed, reducing initial bundle size and improving performance.

  2. Basic Syntax

    import React, { Suspense } from "react";
    
    const About = React.lazy(() => import("./About"));
    
    function App() {
      return (
        <Suspense fallback={<h2>Loading...</h2>}>
          <About />
        </Suspense>
      );
    }
    

    import("./About") → dynamic import (returns a Promise)
    React.lazy → converts it into a component
    Suspense → shows a fallback UI while loading

  3. Why Use React.lazy?
    i) Without Lazy Loading -
    All components are bundled, Even unused pages are loaded upfront.

    import Home from "./Home";
    import About from "./About";
    import Dashboard from "./Dashboard";
    

    ii) With Lazy Loading
    Loaded only when needed

    const About = React.lazy(() => import("./About"));
    
  4. Real-World Use Case (Routing)

    import { BrowserRouter, Routes, Route } from "react-router-dom";
    import { Suspense } from "react";
    
    const Home = React.lazy(() => import("./Home"));
    const About = React.lazy(() => import("./About"));
    
    function App() {
      return (
        <BrowserRouter>
          <Suspense fallback={<h2>Loading Page...</h2>}>
            <Routes>
              <Route path="/" element={<Home />} />
              <Route path="/about" element={<About />} />
            </Routes>
          </Suspense>
        </BrowserRouter>
      );
    }
    

    You must wrap lazy components with Suspense

    <Suspense fallback={<Loader />}>
      <LazyComponent />
    </Suspense>
    
  5. When to Use React.lazy
    Use it for:
    i) Route-based components
    ii) Large components
    iii) Admin/dashboard pages
    iv) Rarely used features