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.