Learn the concept
Data Fetching
In the App Router, data is fetched directly in Server Components using `async/await` with opt-in caching via \"use cache\". The Pages Router uses special functions like `getStaticProps` (build time) and `getServerSideProps` (request time).
App Router Data Fetching:
Server Components can be async and fetch data directly:
async function Page() {
const data = await fetch('...');
}Caching in Next.js 16 (Opt-In Model):
cacheLife() for time-based revalidation profilescacheTag() for on-demand revalidation with revalidateTag()Legacy Caching Options:
{ cache: 'no-store' } - No caching (SSR){ next: { revalidate: 60 } } - ISR (revalidate after 60s)Pages Router Data Fetching:
getStaticProps - Build time (SSG)getStaticPaths - Dynamic routes for SSGgetServerSideProps - Request time (SSR)Client-Side Fetching:
useEffect + useState (manual approach)Parallel vs Sequential:
Promise.all for parallel fetches// app/posts/page.tsx - Server Component
// NOT cached by default in Next.js 16 — use \"use cache\" for caching
async function getPosts() {
const res = await fetch('https://api.example.com/posts');
if (!res.ok) throw new Error('Failed to fetch posts');
return res.json();
}
export default async function PostsPage() {
const posts = await getPosts();
return (
<ul>
{posts.map((post: any) => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
// With revalidation (ISR)
async function getPostsISR() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 3600 }, // Revalidate every hour
});
return res.json();
}
// Force dynamic (SSR)
async function getPostsSSR() {
const res = await fetch('https://api.example.com/posts', {
cache: 'no-store', // Always fetch fresh
});
return res.json();
}Fetching CMS content in Server Components with on-demand revalidation when editors publish changes
Combining server-side data fetching for initial load with SWR for client-side real-time updates
Using parallel fetches in Server Components to aggregate data from multiple microservices into a single page
Build a page demonstrating sequential vs parallel fetching, caching with use cache, and client-side SWR polling
Build a blog that fetches from a headless CMS with use cache and cacheTag for on-demand revalidation on publish