Server vs Client Components — How to Decide
Component design చేసేటప్పుడు, ఈ ఒక్క question అడగండి: "ఈ component కి interactivity (state, event handlers, browser APIs) కావాలా?"
- NO → Server Component గా ఉంచండి (default, ఏమీ చేయనవసరం లేదు)
- YES → ఆ specific piece ni "use client" Component గా extract చేయండి
| Use Case | Component Type | Why |
|---|---|---|
| Blog post content, product descriptions | Server | Static, no interactivity needed |
| Like button, add-to-cart button | Client | Needs onClick + state |
| Search bar with live filtering | Client | Needs useState for input value |
| Navigation bar (static links) | Server | Just renders links, no state |
| Dropdown menu (open/close toggle) | Client | Needs useState for open state |
| Database-driven data table (read-only) | Server | Just fetches & displays data |
Most common real-world pattern — page mొత్తం Server Component గా ఉంచి, interactivity అవసరమైన చిన్న "islands" matrame Client Components గా extract చేయడం:
import AddToCartButton from "./AddToCartButton";
export default async function ProductPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
const product = await fetch(`https://api.example.com/products/${id}`).then((r) => r.json());
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<AddToCartButton productId={id} />
</div>
);
}
Page itself Server Component — data fetching direct ga జరుగుతుంది. productId (string, serializable) matrame AddToCartButton (separate "use client" file) కి pass అవుతుంది — cart logic client meedhа pని చేస్తుంది.
Page లో ఒక్క button కి interactivity కావాలని, page.tsx మొత్తం top లో 'use client' pెట్టడం — chాలా common mistake. బదులు, ఆ button ని matrame separate client component గా extract చేసి, parent Server Component గానే ఉంచాలి.
Given a blog post page that fetches content from an API, extract just the 'Share' button into its own client component, keeping the rest server-rendered.
"use client";
export default function ShareButton({ url }: { url: string }) {
return (
<button onClick={() => navigator.clipboard.writeText(url)}>
Share This Post
</button>
);
}
Q Small projects lో anni components Client గా pెట్టవచ్చా?
Technically avunu, kani performance benefits (small bundle, fast load, SEO) anni pోతాయి. Production apps కి, ఈ decision framework follow చేయడం strongly recommended.
Q Server Component నుండి Client Component కి function pass చేయవచ్చా?
Ledు, functions serializable కావు (except pre-defined Server Actions, Chapter 21 లో చూద్దాం). Strings, numbers, objects, arrays matrame pass చేయవచ్చు.
Q ఈ decision framework ప్రతి project కి same గా apply అవుతుందా?
Core principle (static → Server, interactive → Client) ఎప్పుడూ apply అవుతుంది, kani exact boundary placement project UX requirements meedha depend అవుతుంది.