React Suspense — Streaming and Lazy Loading
Advertisement
React Suspense — Streaming and Lazy Loading
Suspense enables progressive rendering, allowing parts of your UI to load at different times.
Code Splitting
import dynamic from 'next/dynamic'
import { Suspense } from 'react'
const HeavyComponent = dynamic(() => import('@/components/heavy'))
export default function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<HeavyComponent />
</Suspense>
)
}
Streaming
Stream content progressively:
export default function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<Suspense fallback={<HeaderSkeleton />}>
<Header />
</Suspense>
<Suspense fallback={<ContentSkeleton />}>
<MainContent />
</Suspense>
<Suspense fallback={<SidebarSkeleton />}>
<Sidebar />
</Suspense>
</div>
)
}
Async Components
async function UserData() {
const user = await fetch('/api/user').then(r => r.json())
return <div>{user.name}</div>
}
export default function Page() {
return (
<Suspense fallback={<div>Loading user...</div>}>
<UserData />
</Suspense>
)
}
FAQ
Q: What's the difference between Suspense and loading.tsx? A: Suspense is granular and component-level. loading.tsx wraps entire route segments.
Q: Can I use Suspense for error boundaries? A: Use Error Boundaries for errors, Suspense for async.
Q: Does Suspense work with all async operations? A: Works with code splitting and async Server Components. Not with useEffect.
Suspense enables sophisticated progressive rendering patterns.
Advertisement