react-server-components
Implements React Server Components (RSC) patterns with Next.js App Router including data fetching, streaming, selective hydration, and server/client composition. Use when users request "server components", "RSC", "Next.js app router", "server-side rendering", or "streaming".
What this skill does
# React Server Components
Build performant applications with React Server Components and Next.js App Router.
## Core Workflow
1. **Understand RSC model**: Server vs client components
2. **Design component tree**: Plan server/client boundaries
3. **Implement data fetching**: Fetch in server components
4. **Add interactivity**: Client components where needed
5. **Enable streaming**: Suspense for progressive loading
6. **Optimize**: Minimize client bundle size
## Server vs Client Components
### Key Differences
| Feature | Server Components | Client Components |
|---------|-------------------|-------------------|
| Rendering | Server only | Server + Client |
| Bundle size | Zero JS sent | Adds to bundle |
| Data fetching | Direct DB/API access | useEffect/TanStack Query |
| State/Effects | No hooks | Full React hooks |
| Event handlers | No | Yes |
| Browser APIs | No | Yes |
| File directive | Default (none) | `'use client'` |
### When to Use Each
**Server Components (Default)**
- Static content
- Data fetching
- Backend resource access
- Large dependencies (markdown, syntax highlighting)
- Sensitive logic/tokens
**Client Components**
- Interactive UI (onClick, onChange)
- useState, useEffect, useReducer
- Browser APIs (localStorage, geolocation)
- Custom hooks with state
- Third-party client libraries
## Basic Patterns
### Server Component (Default)
```tsx
// app/users/page.tsx (Server Component - no directive needed)
import { db } from '@/lib/db';
async function getUsers() {
return db.user.findMany({
orderBy: { createdAt: 'desc' },
});
}
export default async function UsersPage() {
const users = await getUsers();
return (
<div>
<h1>Users</h1>
<ul>
{users.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
```
### Client Component
```tsx
// components/Counter.tsx
'use client';
import { useState } from 'react';
export function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
```
### Composition Pattern
```tsx
// app/dashboard/page.tsx (Server Component)
import { db } from '@/lib/db';
import { DashboardClient } from './DashboardClient';
import { StatsCard } from '@/components/StatsCard';
async function getStats() {
const [users, orders, revenue] = await Promise.all([
db.user.count(),
db.order.count(),
db.order.aggregate({ _sum: { total: true } }),
]);
return { users, orders, revenue: revenue._sum.total };
}
export default async function DashboardPage() {
const stats = await getStats();
return (
<div>
{/* Server-rendered static content */}
<h1>Dashboard</h1>
{/* Server components with data */}
<div className="grid grid-cols-3 gap-4">
<StatsCard title="Users" value={stats.users} />
<StatsCard title="Orders" value={stats.orders} />
<StatsCard title="Revenue" value={`$${stats.revenue}`} />
</div>
{/* Client component for interactivity */}
<DashboardClient initialData={stats} />
</div>
);
}
```
```tsx
// app/dashboard/DashboardClient.tsx
'use client';
import { useState } from 'react';
import { DateRangePicker } from '@/components/DateRangePicker';
import { Chart } from '@/components/Chart';
interface DashboardClientProps {
initialData: Stats;
}
export function DashboardClient({ initialData }: DashboardClientProps) {
const [dateRange, setDateRange] = useState({ from: null, to: null });
return (
<div>
<DateRangePicker value={dateRange} onChange={setDateRange} />
<Chart data={initialData} />
</div>
);
}
```
## Data Fetching Patterns
### Parallel Data Fetching
```tsx
// app/page.tsx
async function getUser(id: string) {
const res = await fetch(`/api/users/${id}`);
return res.json();
}
async function getPosts(userId: string) {
const res = await fetch(`/api/users/${userId}/posts`);
return res.json();
}
async function getComments(userId: string) {
const res = await fetch(`/api/users/${userId}/comments`);
return res.json();
}
export default async function ProfilePage({ params }: { params: { id: string } }) {
// Parallel fetching - all requests start simultaneously
const [user, posts, comments] = await Promise.all([
getUser(params.id),
getPosts(params.id),
getComments(params.id),
]);
return (
<div>
<UserHeader user={user} />
<PostsList posts={posts} />
<CommentsList comments={comments} />
</div>
);
}
```
### Sequential Data Fetching (When Dependent)
```tsx
export default async function OrderPage({ params }: { params: { id: string } }) {
// Sequential - second fetch depends on first
const order = await getOrder(params.id);
const customer = await getCustomer(order.customerId);
return (
<div>
<OrderDetails order={order} />
<CustomerInfo customer={customer} />
</div>
);
}
```
### Caching and Revalidation
```tsx
// Static data (cached indefinitely)
async function getStaticData() {
const res = await fetch('https://api.example.com/static', {
cache: 'force-cache', // Default
});
return res.json();
}
// Dynamic data (no cache)
async function getDynamicData() {
const res = await fetch('https://api.example.com/dynamic', {
cache: 'no-store',
});
return res.json();
}
// Revalidate after time
async function getRevalidatedData() {
const res = await fetch('https://api.example.com/data', {
next: { revalidate: 3600 }, // Revalidate every hour
});
return res.json();
}
// Revalidate by tag
async function getTaggedData() {
const res = await fetch('https://api.example.com/products', {
next: { tags: ['products'] },
});
return res.json();
}
// Trigger revalidation
import { revalidateTag } from 'next/cache';
revalidateTag('products');
```
## Streaming with Suspense
### Page-Level Streaming
```tsx
// app/dashboard/page.tsx
import { Suspense } from 'react';
import { StatsCards, StatsCardsSkeleton } from './StatsCards';
import { RecentOrders, RecentOrdersSkeleton } from './RecentOrders';
import { TopProducts, TopProductsSkeleton } from './TopProducts';
export default function DashboardPage() {
return (
<div>
<h1>Dashboard</h1>
{/* Each section streams independently */}
<Suspense fallback={<StatsCardsSkeleton />}>
<StatsCards />
</Suspense>
<div className="grid grid-cols-2 gap-4 mt-8">
<Suspense fallback={<RecentOrdersSkeleton />}>
<RecentOrders />
</Suspense>
<Suspense fallback={<TopProductsSkeleton />}>
<TopProducts />
</Suspense>
</div>
</div>
);
}
```
### Component with Data
```tsx
// app/dashboard/StatsCards.tsx
import { db } from '@/lib/db';
async function getStats() {
// Simulate slow query
await new Promise((resolve) => setTimeout(resolve, 2000));
return db.stats.findFirst();
}
export async function StatsCards() {
const stats = await getStats();
return (
<div className="grid grid-cols-4 gap-4">
<Card title="Revenue" value={stats.revenue} />
<Card title="Orders" value={stats.orders} />
<Card title="Customers" value={stats.customers} />
<Card title="Products" value={stats.products} />
</div>
);
}
export function StatsCardsSkeleton() {
return (
<div className="grid grid-cols-4 gap-4">
{[...Array(4)].map((_, i) => (
<div key={i} className="h-24 bg-gray-200 animate-pulse rounded" />
))}
</div>
);
}
```
### Loading States
```tsx
// app/products/loading.tsx
export default function ProductsLoading() {
return (
<div className="grid grid-cols-3 gap-4">
{[...Array(9)].map((_, i) => (
<div key={i} className="h-64 bg-gray-200 animate-pulse rounded" />
))}
</div>
);
}
```
## Server Actions
### Form Actions
```tsx
// app/contact/page.tsx
import { submitContact } from './actions';
expoRelated in Web Dev
generating-lwc-components
IncludedLightning Web Components with PICKLES methodology and 165-point scoring. Use this skill when the user creates or edits LWC components, builds wire service patterns, or writes Jest tests for LWC. TRIGGER when: user creates/edits LWC components, touches lwc/**/*.js, .html, .css, .js-meta.xml files, or asks about wire service, SLDS, or Jest LWC tests. DO NOT TRIGGER when: Apex classes (use generating-apex), Aura components, or Visualforce.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Set up queries with useQuery, mutations with useMutation, configure QueryClient caching strategies, implement optimistic updates, and handle infinite scroll with useInfiniteQuery. Use when: setting up data fetching in React projects, migrating from v4 to v5, or fixing object syntax required errors, query callbacks removed issues, cacheTime renamed to gcTime, isPending vs isLoading confusion, keepPreviousData removed problems.
document-processor-api
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
nutrient-document-processing
IncludedProcess documents with Nutrient DWS. Use when the user wants to generate PDFs from HTML or URLs, convert Office/images/PDFs, assemble or split packets, OCR scans, extract text/tables/key-value pairs, redact PII, watermark, sign, fill forms, optimize PDFs, or produce compliance outputs like PDF/A or PDF/UA. Triggers include convert to PDF, merge these PDFs, OCR this scan, extract tables, redact PII, sign this PDF, make this PDF/A, or linearize for web delivery.
tanstack-query
IncludedManage server state in React with TanStack Query v5. Covers useMutationState, simplified optimistic updates, throwOnError, network mode (offline/PWA), and infiniteQueryOptions. Use when setting up data fetching, fixing v4→v5 migration errors (object syntax, gcTime, isPending, keepPreviousData), or debugging SSR/hydration issues with streaming server components.
accelint-nextjs-best-practices
IncludedNext.js performance optimization and best practices. Use when writing Next.js code (App Router or Pages Router); implementing Server Components, Server Actions, or API routes; optimizing RSC serialization, data fetching, or server-side rendering; reviewing Next.js code for performance issues; fixing authentication in Server Actions; or implementing Suspense boundaries, parallel data fetching, or request deduplication.