React Suspense Tutorials
Web Development
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
plaintext
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)
plaintext
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
plaintext
import { lazy } from "react";Step 2: Load component dynamically
plaintext
const Cars = lazy(() => import("./Cars"));Step 3: Wrap with Suspense
plaintext
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
plaintext
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