REACT & NEXT.JS / 6. SERVER VS CLIENT COMPONENTS
Server vs Client Components
The most important mental model in Next.js App Router
EXPLANATION
This is the biggest shift in Next.js 13+. Every component is a Server Component by default. Server Components: • Run only on the server, never sent to the browser as JS • Can directly access databases, file system, environment variables • Cannot use useState, useEffect, event handlers, browser APIs • Reduce client-side JavaScript bundle significantly Client Components: • Add "use client" directive at top of file • Run on both server (for initial HTML) and client (for interactivity) • Can use hooks, event handlers, browser APIs • Needed for: useState, useEffect, onClick, window, localStorage The composition pattern: • Server Component fetches data, passes it as props to a Client Component • "Push state down, push data up" — keep interactivity at the leaf level Common mistake: marking an entire page as "use client" just because one small part needs interactivity. Instead, extract just the interactive part into its own Client Component and keep the parent as a Server Component.
DIAGRAM
✓ CORRECT: server wraps client
ServerPage (server) ← fetches data, no JS bundle
└── <StaticContent /> ← server component
└── <InteractiveButton /> ← "use client" (small JS chunk)
✗ WRONG: unnecessary "use client" on parent
Page ("use client") ← entire tree becomes client JS!
└── <StaticContent /> ← now also client (unnecessary)
└── <InteractiveButton /> ← client
Server Components CAN: Client Components CAN:
✓ async/await ✓ useState, useEffect
✓ fetch() with caching ✓ onClick, onChange
✓ access DB directly ✓ browser APIs
✓ read env variables ✓ custom hooks
✗ hooks ✗ async at component level
✗ event handlers ✗ direct DB accessCODE