Master React Server Components data fetching patterns. Server-only queries, streaming with Suspense, waterfall prevention, and cache strategies.
## Task Implement key React Server Components data fetching patterns. ## Requirements - Next.js 15+ with App Router - React 19+ Server Components - TypeScript strict mode ## Patterns to Implement ### 1. Parallel Data Fetching (avoid waterfalls) ```typescript // BAD: sequential (waterfall) const user = await getUser(id); const posts = await getPosts(user.id); // waits for user // GOOD: parallel const [user, posts] = await Promise.all([ getUser(id), getPosts(id), // runs simultaneously ]); ``` ### 2. Streaming with Suspense Boundaries ```typescript // Shell loads instantly, heavy data streams in export default function Page() { return ( <div> <Header /> {/* renders immediately */} <Suspense fallback={<PostsSkeleton />}> <PostsList /> {/* async server component — streams when ready */} </Suspense> <Suspense fallback={<CommentsSkeleton />}> <Comments /> {/* independent stream */} </Suspense> </div> ); } ``` ### 3. Cache & Revalidation ```typescript // Per-request deduplication (React cache) const getUser = cache(async (id: string) => { return db.user.findUnique({ where: { id } }); }); // Time-based revalidation export const revalidate = 60; // seconds // On-demand revalidation after mutation revalidateTag("posts"); ``` ### 4. Server-Only Code ```typescript import "server-only"; // Throws if imported in client bundle import { db } from "./db"; // Safe — never reaches the client ``` ## Implementation Notes 1. Default to Server Components — only use "use client" when needed 2. Pass serializable props from server to client components 3. Use `loading.tsx` for page-level suspense, `<Suspense>` for granular 4. Avoid fetching in client components — pass data down from server 5. Use `notFound()` and `redirect()` for flow control in server components
No gallery images yet.