React Suspense
React Suspense is a feature that allows components to wait (suspend rendering) until something is ready (like code or data).
While waiting, it shows fallback UI (loading state).
Why Use Suspense?
In real applications:
Components take time to load
Data fetching takes time
Large bundles slow down UI
Suspense helps by:
โ Showing a loading UI
โ Improving user experience
โ Handling async rendering smoothly
Common Use Cases
Lazy loading components (
React.lazy)Data fetching (with frameworks like Next.js, Relay, etc.)
Code splitting (performance optimization)
Basic Usage
import { Suspense } from "react";
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>๐น How It Works
Component is loading
Suspense shows โ
fallbackOnce ready โ actual component renders
Example (Basic)
import { Suspense } from "react";
import Fruits from "./Fruits";
function App() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<Fruits />
</Suspense>
</div>
);
} If Fruits takes time โ "Loading..." will show
Suspense with Lazy Loading
Step 1: Import lazy
import { lazy } from "react";Step 2: Load component dynamically
const Cars = lazy(() => import("./Cars"));Step 3: Wrap with Suspense
import { Suspense, lazy } from "react";
const Cars = lazy(() => import("./Cars"));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Cars />
</Suspense>
);
}How lazy() Works
Loads component only when needed
Reduces initial bundle size
Improves performance
Without Lazy vs With Lazy
โ Without Lazy
All components load at once
Bigger bundle size
Slower initial load
With Lazy + Suspense
Components load on demand
Smaller bundle
Faster app
Multiple Components Example
import { Suspense, lazy } from "react";
const Header = lazy(() => import("./Header"));
const Sidebar = lazy(() => import("./Sidebar"));
const Content = lazy(() => import("./Content"));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Header />
<div style={{ display: "flex" }}>
<Sidebar />
<Content />
</div>
</Suspense>
);
}One Suspense can handle multiple components
Key Points
Suspense shows fallback UI while loading
Works best with
lazy()Improves performance (code splitting)
Makes UX smoother
Interview Questions
What is React Suspense?
What is fallback in Suspense?
Difference between lazy loading and normal import?
How does Suspense improve performance?
Can Suspense handle multiple components?
๐งพ Summary
Suspenseโ loading UI handlerfallbackโ what user sees while loadinglazy()โ dynamic importUsed for โ performance + better UX