JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionsnextjs
PrevNext
nextjs
mid
components

What's the difference between Server Components and Client Components in Next.js?

nextjs
server-components
client-components
use-client
react
ssr
Quick Answer

Server Components render on the server with no JavaScript sent to the client, ideal for data fetching and static content. Client Components (marked with 'use client') render on both server and client, enabling interactivity like state and event handlers.

Detailed Explanation

Server Components (Default in App Router):

  • Render only on the server
  • No JavaScript shipped to client
  • Can await data directly
  • Can access backend resources (DB, files, secrets)
  • Cannot use: useState, useEffect, event handlers, browser APIs

Client Components:

  • Add 'use client' directive at top of file
  • Render on server (SSR), then hydrate on client
  • JavaScript sent to browser
  • Can use React hooks and browser APIs
  • Required for interactivity

Composition Pattern:

  • Keep most components as Server Components
  • Use Client Components only where needed
  • Server Components can import Client Components
  • Client Components cannot import Server Components directly (use children pattern)

Best Practice:

  • Move 'use client' as far down the tree as possible
  • Only wrap the interactive parts in Client Components

Code Examples

Server Component (default)
// app/posts/page.tsx - Server Component
// No 'use client' = Server Component by default

import { db } from '@/lib/db'; // Can access DB directly!

export default async function PostsPage() {
  // ✅ Can await data directly
  const posts = await db.posts.findMany();
  
  // ✅ Can access server-only resources
  const apiKey = process.env.SECRET_API_KEY;
  
  // ❌ Cannot use hooks
  // const [count, setCount] = useState(0); // Error!
  
  // ❌ Cannot use event handlers directly
  // <button onClick={() => {}}>Click</button> // Error!
  
  return (
    <div>
      <h1>Posts</h1>
      {posts.map((post) => (
        <article key={post.id}>
          <h2>{post.title}</h2>
          <p>{post.content}</p>
        </article>
      ))}
    </div>
  );
}

Resources

Server and Client Components

docs

Composition Patterns

docs

Related Questions

What are the key differences between Pages Router and App Router in Next.js?

mid
routing

What are Server Actions in Next.js and how do they handle form submissions and mutations?

senior
server-actions
Previous
How does data fetching work in Next.js?
Next
How do you create dynamic routes with static generation in Next.js?