);
}
```
### Streaming with Suspense
```typescript
// app/page.tsx
import { Suspense } from 'react';
import { SlowComponent, FastComponent } from '@/components';
export default function Page() {
return (
{/* Fast content renders immediately */}
{/* Slow content streams in */}
Loading slow content...}>
);
}
// components/slow-component.tsx
async function getSlowData() {
await new Promise((resolve) => setTimeout(resolve, 2000));
return { data: 'Slow data loaded' };
}
export async function SlowComponent() {
const data = await getSlowData();
return
{data.data}
;
}
```
### Server Actions
```typescript
// app/actions.ts
'use server';
import { revalidatePath } from 'next/cache';
import { db } from '@/lib/db';
export async function createUser(formData: FormData) {
const name = formData.get('name') as string;
const email = formData.get('email') as string;
await db.user.create({
data: { name, email },
});
revalidatePath('/users');
}
export async function updateUser(id: string, formData: FormData) {
const name = formData.get('name') as string;
await db.user.update({
where: { id },
data: { name },
});
revalidatePath(`/users/${id}`);
}
// components/user-form.tsx
'use client';
import { useFormStatus } from 'react-dom';
import { createUser } from '@/app/actions';
function SubmitButton() {
const { pending } = useFormStatus();
return (
);
}
export function UserForm() {
return (
);
}
```
### Passing Server Components as Props
```typescript
// Pattern: Server Component as children
// app/page.tsx
import { ClientWrapper } from '@/components/client-wrapper';
import { ServerContent } from '@/components/server-content';
export default function Page() {
return (
);
}
// components/client-wrapper.tsx
'use client';
export function ClientWrapper({ children }: { children: React.ReactNode }) {
const [isOpen, setIsOpen] = useState(true);
return (
{isOpen && children}
);
}
```
## Decision Framework
### Use Server Components When:
- Fetching data
- Accessing backend resources directly
- Keeping sensitive information on server
- Keeping large dependencies on server
- No interactivity needed
### Use Client Components When:
- Using useState, useEffect, useReducer
- Using browser APIs
- Adding event listeners
- Using custom hooks with state
- Using React Context providers
## Best Practices
- Default to Server Components
- Push client boundaries down the tree
- Pass serializable props to client components
- Use Suspense for streaming
- Colocate data fetching with components
## Target Processes
- nextjs-full-stack
- react-server-components-migration
- performance-optimization
- streaming-implementation