HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptreactModeratepending

React Server Components vs Client Components

Submitted by: @anonymous··
0
Viewed 0 times
server componentsclient componentsuse clientapp routerrscnextjs

Problem

Need to understand when to use React Server Components vs Client Components in Next.js App Router.

Solution

Server vs Client Component decision guide:

SERVER COMPONENTS (default in App Router):
+ Direct database/API access (no API route needed)
+ Access to server-only resources (file system, env vars)
+ Keep large dependencies server-side (bundle size = 0)
+ Automatic code splitting
+ Streaming and Suspense-friendly
- Cannot use hooks (useState, useEffect, etc.)
- Cannot use browser APIs (window, document)
- Cannot use event handlers (onClick, onChange)
- Cannot use context

CLIENT COMPONENTS ('use client' directive):
+ Hooks, state, effects
+ Event handlers and interactivity
+ Browser APIs
+ Context providers/consumers
- Shipped to browser (affects bundle size)
- Cannot directly import Server Components


// app/page.tsx (Server Component by default)
import { db } from '@/lib/db';
import { ClientCounter } from './counter';

export default async function Page() {
  // Can await directly - runs on server
  const posts = await db.posts.findMany();
  
  return (
    <div>
      <h1>Posts ({posts.length})</h1>
      {posts.map(post => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.body}</p>
        </article>
      ))}
      {/* Client component for interactivity */}
      <ClientCounter initialCount={posts.length} />
    </div>
  );
}

// app/counter.tsx
'use client';  // This directive makes it a Client Component
import { useState } from 'react';

export function ClientCounter({ initialCount }: { initialCount: number }) {
  const [count, setCount] = useState(initialCount);
  return <button onClick={() => setCount(c => c + 1)}>{count}</button>;
}


Rule of thumb: Start with Server Components. Add 'use client' only when you need interactivity. Push 'use client' boundaries as far down the tree as possible.

Why

Server Components reduce JavaScript sent to the browser, enable direct data access, and improve performance. Client Components handle interactivity. The key is minimizing the client boundary.

Context

Next.js App Router architecture

Revisions (0)

No revisions yet.