patternjavascriptreactMajorpendingCanonical
React Server Components vs Client Components Decision Guide
Viewed 0 times
React Server ComponentsRSCuse clientNext.jsApp Routerserver vs client
Problem
React Server Components (RSC) change how you think about component architecture. Unclear when to use server vs client components and how they interact.
Solution
Decision framework for component type:
Use Server Components (default) when:
Use Client Components ('use client') when:
Composition pattern: Server wraps Client
Key rules:
Use Server Components (default) when:
- Fetching data (direct DB/API access)
- Accessing server-only resources (env vars, filesystem)
- Rendering static or cacheable content
- Large dependencies only needed for rendering (markdown parsers, syntax highlighters)
// Server Component (default in Next.js App Router)
async function ProductPage({ id }) {
const product = await db.products.findUnique({ where: { id } });
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<AddToCartButton productId={id} /> {/* Client component */}
</div>
);
}Use Client Components ('use client') when:
- Interactive UI (onClick, onChange, onSubmit)
- useState, useEffect, useRef, useContext
- Browser APIs (localStorage, geolocation)
- Custom hooks that use state/effects
- Third-party client libraries
'use client';
function AddToCartButton({ productId }) {
const [loading, setLoading] = useState(false);
return (
<button onClick={async () => {
setLoading(true);
await addToCart(productId);
setLoading(false);
}}>
{loading ? 'Adding...' : 'Add to Cart'}
</button>
);
}Composition pattern: Server wraps Client
// Server Component fetches data, passes to Client Component
async function Dashboard() {
const data = await fetchAnalytics(); // Server-side
return <InteractiveChart data={data} />; // Client renders it
}Key rules:
- Server Components can import Client Components
- Client Components CANNOT import Server Components
- You can pass Server Components as children to Client Components
- 'use client' marks the boundary - everything imported is also client
Why
Server Components reduce bundle size (server-only code never ships to browser), enable direct data access, and improve initial page load. But interactivity requires Client Components.
Gotchas
- 'use client' doesn't mean it only runs on client - it runs on server for SSR too
- Passing functions as props across the server/client boundary is not allowed
Context
Architecting React applications with Server Components
Revisions (0)
No revisions yet.