← Back to Chapters

React Suspense & Lazy Loading

⚛️ React Suspense & Lazy Loading

? Quick Overview

React Suspense and lazy loading help load components only when required, reducing bundle size and improving performance.

? Key Concepts

  • Code splitting
  • Dynamic imports
  • Fallback UI
  • Deferred loading

? Syntax & Theory

React.lazy() dynamically imports a component, while <Suspense> displays fallback UI during loading.

? Code Example — Lazy Component

? View Code Example
// Lazy-loaded component definition
import React from "react";
export default function LazyComponent() {
return <h3>This component was loaded lazily!</h3>;
}

? Code Example — Using Suspense

? View Code Example
// App component using React.lazy and Suspense
import React, { lazy, Suspense } from "react";

const LazyComponent = lazy(() => import("./LazyComponent"));

function App() {
return (
<Suspense fallback={<p>Loading component...</p>}>
<LazyComponent />
</Suspense>
);
}

export default App;

? Live Output / Explanation

When the app loads, React shows the fallback UI first. Once the component finishes loading, it replaces the fallback.

⚙️ Lazy Loading with Routing

? View Code Example
// Route-based code splitting using React Router
import React, { Suspense, lazy } from "react";
import { Routes, Route } from "react-router-dom";

const Home = lazy(() => import("./pages/Home"));
const About = lazy(() => import("./pages/About"));

function App() {
return (
<Suspense fallback={<div>Loading Page...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
);
}

⚡ Interactive Simulation

Click the button below to simulate how Suspense works. This mimics a 2-second network delay.

? Interactive Flow Diagram

User Action → Suspense Boundary → Fallback UI → Lazy Component Loaded → UI Updated

? Tips & Best Practices

  • Always use meaningful fallback UI
  • Lazy load large components only
  • Use nested Suspense for smoother UX
  • Combine with routing for best performance

? Try It Yourself

  1. Create a lazy-loaded component
  2. Add a custom fallback loader
  3. Apply lazy loading to routes
  4. Experiment with nested Suspense

Goal: Optimize performance and user experience.