Next.js データフェッチ
ルール
- サーバーコンポーネントで async/await を使って fetch を行います。初期データに
useEffect は使いません。
fetch() は App Router ではデフォルトでキャッシュされます。{ cache: 'no-store' } または next: { revalidate } でその挙動を変更できます。どちらが必要か把握してください。
- 独立したリクエストは
Promise.all で並列化します。依存関係がある場合のみ逐次実行します。
- 遅いセクションは
<Suspense fallback> + loading.tsx でラップし、ストリーミングを有効にします。
- オンデマンドの無効化には
next: { tags: ['posts'] } + revalidateTag('posts') を使用します。
- クライアントサイドフェッチ(SWR/React Query)はインタラクティブやフィルタリングが必要なUIのみに使用し、初回描画には使いません。
パターン
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
next: { revalidate: 60 },
});
if (!res.ok) throw new Error('Failed to fetch posts');
return res.json();
}
async function getInbox(userId: string) {
const res = await fetch(`https://api.example.com/inbox/${userId}`, {
cache: 'no-store',
});
return res.json();
}
export default async function Dashboard() {
const [user, posts] = await Promise.all([getUser(), getPosts()]);
return <View user={user} posts={posts} />;
}
import { Suspense } from 'react';
export default function Page() {
return (
<div>
<FastHeader />
<Suspense fallback={<CommentsSkeleton />}>
<SlowComments />
</Suspense>
</div>
);
}
import { revalidateTag } from 'next/cache';
export async function POST(req: Request) {
const { tag, secret } = await req.json();
if (secret !== process.env.REVALIDATE_SECRET)
return Response.json({ ok: false }, { status: 401 });
revalidateTag(tag);
return Response.json({ ok: true });
}
チェックリスト