← Back to Chapters

React.lazy()

? React.lazy()

? Quick Overview

React.lazy() enables component-level code splitting, allowing parts of an application to load only when required. This reduces initial bundle size and improves performance.

? Key Concepts

  • Lazy loading components on demand
  • Dynamic imports using import()
  • Fallback UI with <Suspense>

? Syntax & Theory

? View Code Example
// lazy() dynamically imports a component
const MyComponent = React.lazy(() => import("./MyComponent"));

? Without Code Splitting

All components load together during app startup, increasing load time.

? View Code Example
// All components bundled at once
import Header from "./Header";
import Footer from "./Footer";
import Dashboard from "./Dashboard";

✅ Using React.lazy()

Components are loaded only when required.

? View Code Example
// Components are loaded on demand
const Dashboard = React.lazy(() => import("./Dashboard"));

? Combining with Routing

? View Code Example
// Pages load only when route is visited
const Home = React.lazy(() => import("./pages/Home"));

? Live Output / Explanation

When a user navigates to a lazily loaded component, React fetches the required JavaScript chunk and displays the fallback UI until loading completes.

? Use Cases

  • Large dashboards
  • Multi-page React applications
  • Rarely used features

? Interactive Diagram

Initial Load ➜ Core Bundle ➜ User Action ➜ Lazy Component Loaded

? Interactive Simulator

Click the button below to simulate loading a "Heavy Dashboard" component over a slow network. Watch how the fallback (Suspense) appears before the content.

(Simulates network latency)

? Tips & Best Practices

  • Always wrap lazy components inside <Suspense>
  • Use lazy loading for large pages or features
  • Keep fallback UI lightweight

? Try It Yourself

  1. Convert a page component to use React.lazy()
  2. Add a loading spinner fallback
  3. Compare bundle sizes before and after