patternnextjsMajorpending
Next.js Server Components vs Client Components — when to use which
Viewed 0 times
use clientServer ComponentClient ComponentServer ActionsApp RouterRSC
nodejsbrowser
Problem
Confusion about when to use 'use client' directive in Next.js App Router. Server Components can't use useState/useEffect. Client Components can't directly access databases. Mixing them incorrectly causes hydration errors.
Solution
(1) Default is Server Component — no directive needed. Use for: data fetching, accessing backend resources, keeping secrets server-side, reducing client JS. (2) Add 'use client' when you need: useState, useEffect, event handlers (onClick), browser APIs (localStorage, window), third-party hooks. (3) Pattern: Server Component parent fetches data, passes it to Client Component children as props. (4) You CAN import Server Components into Client Components as children (passed via props), but NOT by direct import. (5) Server Components render on the server only — their code never reaches the browser. (6) Forms: use Server Actions (async functions with 'use server') for form submissions without client-side JS.
Why
Server Components reduce the JavaScript sent to the browser by running on the server only. They can directly access databases and APIs without exposing secrets. Client Components handle interactivity.
Revisions (0)
No revisions yet.