29) React.lazy and Suspense
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.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 loadingWhy 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 neededconst About = React.lazy(() => import("./About"));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>When to Use React.lazy
Use it for:
i) Route-based components
ii) Large components
iii) Admin/dashboard pages
iv) Rarely used features