React — Suspense
Basic Suspense
import { Suspense } from 'react';
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
Suspense with Lazy Loading
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading component...</div>}>
<LazyComponent />
</Suspense>
);
}
Multiple Suspense Boundaries
function App() {
return (
<div>
<header>
<Suspense fallback={<div>Loading header...</div>}>
<Header />
</Suspense>
</header>
<main>
<Suspense fallback={<div>Loading content...</div>}>
<Content />
</Suspense>
</main>
<footer>
<Suspense fallback={<div>Loading footer...</div>}>
<Footer />
</Suspense>
</footer>
</div>
);
}
Suspense Examples
// Data fetching with Suspense
function UserProfile({ userId }) {
const user = use(fetchUser(userId));
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
function App() {
return (
<Suspense fallback={<div>Loading user...</div>}>
<UserProfile userId={1} />
</Suspense>
);
}
// Route-based Suspense
const Dashboard = React.lazy(() => import('./pages/Dashboard'));
const Settings = React.lazy(() => import('./pages/Settings'));
function App() {
return (
<Router>
<Suspense fallback={<div>Loading page...</div>}>
<Routes>
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
</Router>
);
}
Mini Practice
Write React code that:
- Uses Suspense with lazy loading
- Creates multiple Suspense boundaries
- Implements route-based Suspense
- Shows loading states
Up Next
Next: Learn about Lazy Loading.
Related Topics
Frequently Asked Questions about Suspense
What is Suspense in React?
Suspense is a fundamental concept in React. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Suspense?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Suspense.
Why is Suspense important in React?
Suspense is essential for React development. Understanding this concept will help you write better code and solve real-world problems more effectively.