React Suspense and lazy loading help load components only when required, reducing bundle size and improving performance.
React.lazy() dynamically imports a component, while <Suspense> displays fallback UI during loading.
// Lazy-loaded component definition
import React from "react";
export default function LazyComponent() {
return <h3>This component was loaded lazily!</h3>;
}
// 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;
When the app loads, React shows the fallback UI first. Once the component finishes loading, it replaces the fallback.
// 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>
);
}
Click the button below to simulate how Suspense works. This mimics a 2-second network delay.
Suspense Fallback...
This content arrived after the bundle was fetched.
User Action → Suspense Boundary → Fallback UI → Lazy Component Loaded → UI Updated
Goal: Optimize performance and user experience.