What is the Suspense pattern and data fetching with it?
Hint
Suspend rendering while async work completes — component throws a Promise; Suspense catches it and shows fallback
Full Answer
Suspense lets components "wait" for something before rendering. The component throws a Promise; React catches it and shows the fallback.
// React.lazy — built-in Suspense integration
const Chart = lazy(() => import('./Chart'));
// React Query with Suspense mode
function UserProfile({ id }) {
// This will suspend (throw) if data isn't ready yet
const { data: user } = useSuspenseQuery({
queryKey: ['user', id],
queryFn: () => fetchUser(id),
});
return <p>{user.name}</p>; // Only renders when data is ready
}
// Wrapping with Suspense
function Page() {
return (
<Suspense fallback={<Skeleton />}>
<UserProfile id={1} />
</Suspense>
);
}
// Nested Suspense — granular loading states
function Dashboard() {
return (
<Suspense fallback={<PageSkeleton />}>
<UserProfile />
<Suspense fallback={<ChartSkeleton />}>
<Chart /> {/* loads independently */}
</Suspense>
</Suspense>
);
}
💡 Suspense eliminates the isLoading + early return pattern. The component is always in a "ready" state — Suspense handles the loading state above it. Combine with Error Boundaries for complete coverage.
More Advanced Patterns Questions
Practice this in a timed sprint
5 free questions, no signup required