Suspense Patterns
Data fetching with Suspense, error boundaries, loading states, and streaming.
Overview
Suspense lets you wait for something before rendering and show a fallback.
Key Concepts
- Suspense Boundaries — Wrap components that may suspend
- Fallback UI — Show loading state while suspended
- Error Boundaries — Catch errors from suspended components
- Streaming — Progressively send HTML from server
- use() — Read promises and context in render
Code Examples
// Suspense for data fetching
function App() {
return (
<Suspense fallback={<PageSkeleton />}>
<MainContent />
</Suspense>
);
}
async function MainContent() {
const data = await fetchData(); // This suspends
return <DataView data={data} />;
}
// Multiple Suspense boundaries
function Dashboard() {
return (
<div className="dashboard">
<Suspense fallback={<StatsSkeleton />}>
<Stats />
</Suspense>
<Suspense fallback={<ChartSkeleton />}>
<Chart />
</Suspense>
<Suspense fallback={<TableSkeleton />}>
<DataTable />
</Suspense>
</div>
);
}
// Error boundary + Suspense
function SafeComponent() {
return (
<ErrorBoundary fallback={<ErrorUI />}>
<Suspense fallback={<Loading />}>
<AsyncComponent />
</Suspense>
</ErrorBoundary>
);
}
Practice
Build a dashboard with parallel data fetching using multiple Suspense boundaries.