Data Fetching
Server components, caching, revalidation, streaming, and parallel data fetching.
Overview
Next.js provides multiple strategies for fetching data efficiently on the server and client.
Key Concepts
- Server Component Fetching — Direct async/await in components
- Caching —
next/cachefor request deduplication - Revalidation — Time-based or on-demand cache invalidation
- Streaming — Progressive rendering with Suspense
- Parallel Fetching — Fetch multiple data sources simultaneously
Code Examples
// Server component with caching
async function ProductPage({ params }) {
const product = await fetch(`https://api.example.com/products/${params.id}`, {
next: { revalidate: 3600 } // Cache for 1 hour
}).then(res => res.json());
return <ProductDetails product={product} />;
}
// Parallel data fetching
async function Dashboard() {
const [user, posts, analytics] = await Promise.all([
fetchUser(),
fetchPosts(),
fetchAnalytics()
]);
return (
<div>
<UserProfile user={user} />
<PostList posts={posts} />
<AnalyticsChart data={analytics} />
</div>
);
}
// Streaming with Suspense
function Dashboard() {
return (
<div>
<Suspense fallback={<StatsSkeleton />}>
<Stats />
</Suspense>
<Suspense fallback={<ChartSkeleton />}>
<AnalyticsChart />
</Suspense>
</div>
);
}
Practice
Build a dashboard with parallel data fetching and streaming UI.