Server Components và Client Components: ranh giới và composition
Server Component là gì và chạy ở đâu, khi nào cần 'use client', ranh giới lan truyền thế nào, props phải serialize được, truyền Server Component vào Client Component qua children, và chặn code server lọt xuống client.
Đây là thay đổi tư duy lớn nhất khi chuyển từ React SPA sang App Router và là nguồn của phần lớn lỗi: "useState only works
in Client Components", bundle phình to vì đặt 'use client' ở layout gốc, lộ secret vì import nhầm. Nắm chắc module này thì
các module sau trở nên dễ.
🎯 Mục tiêu học tập
- Giải thích Server Component: chạy ở server, không gửi JS, không có state/effect
- Biết chính xác khi nào cần
'use client'và nó lan truyền theo import thế nào - Truyền dữ liệu qua ranh giới: props phải serialize được
- Dùng mẫu children/slot để đặt Server Component bên trong Client Component
- Ngăn code server bị import vào client bằng
server-only - Dùng context provider, thư viện bên thứ ba đúng cách trong App Router
Server Component là mặc định
Trong app/, mọi component là Server Component trừ khi khai báo khác. Nó chạy trên server (lúc build hoặc
lúc request), có thể async, đọc DB/file/secret trực tiếp. Kết quả gửi xuống client là mô tả giao diện (RSC
payload), không phải code của component — nên thư viện dùng trong nó (markdown parser, date lib) không vào bundle.
// app/posts/page.tsx — Server Component
import { db } from '@/lib/db';
import { marked } from 'marked'; // 0 KB gửi xuống client
export default async function Posts() {
const posts = await db.post.findMany({ orderBy: { createdAt: 'desc' }, take: 20 });
return posts.map(p => (
<article key={p.id} dangerouslySetInnerHTML={{ __html: marked(p.body) }} /> // nhớ sanitize nếu body do người dùng nhập
));
}
| Cần | Server | Client |
|---|---|---|
| Fetch dữ liệu, truy cập DB, secret | ✅ | ❌ (qua API) |
| Giảm JS gửi xuống | ✅ | ❌ |
useState, useEffect, useReducer, ref | ❌ | ✅ |
Event handler (onClick, onChange) | ❌ | ✅ |
Browser API (window, localStorage) | ❌ | ✅ |
| Custom hook dùng state/effect, thư viện cần context | ❌ | ✅ |
'use client' là ranh giới, không phải nhãn
'use client' đặt ở đầu file đánh dấu điểm vào của client. File đó và mọi thứ nó import đều thành
code client (vào bundle). Bạn không cần đặt 'use client' ở mọi component tương tác — chỉ ở ranh giới.
app/page.tsx (Server)
├─ Header (Server)
│ └─ SearchBox 'use client' ─► import SearchSuggestions ─► cũng là client
├─ ProductList (Server, query DB)
│ └─ AddToCartButton 'use client' (chỉ cái nút là client, danh sách vẫn ở server)
└─ Footer (Server)
Nguyên tắc: đẩy ranh giới client xuống lá. Đặt 'use client' ở layout gốc biến cả app thành SPA — mất hết
lợi ích RSC.
Lưu ý: Client Component vẫn được render ra HTML trên server ở lần tải đầu (SSR), rồi hydrate ở trình duyệt. "Client"
nghĩa là "có mặt ở client", không phải "chỉ chạy ở client". Vì vậy truy cập window ngay khi render vẫn lỗi — đặt trong effect.
Props qua ranh giới phải serialize được
// Server
<ProductCard
product={{ id: 1, name: 'Áo', price: 199000, createdAt: new Date() }} // ✅ object, Date, Map, Set, BigInt, Promise
onSelect={() => {}} // ❌ hàm thường không serialize được
addToCart={addToCartAction} // ✅ Server Action (hàm 'use server') thì được
/>
Được: giá trị nguyên thuỷ, object/array thuần, Date, Map, Set, typed array, Promise (client đọc bằng use()),
JSX (Server Component đã render), Server Action. Không được: hàm thường, class instance, Symbol không đăng ký.
Truyền nguyên object
user từ DB xuống Client Component là gửi luôn passwordHash, email, role vào RSC payload — ai cũng đọc được trong tab
Network. Chỉ truyền đúng field cần (DTO — Module 10) và dùng taint API (Module 16).
Đặt Server Component bên trong Client Component
Client Component không thể import Server Component (import vào file client là thành client). Nhưng nó có thể
nhận Server Component đã render qua props (children hoặc slot):
// app/_components/Modal.tsx
'use client';
export function Modal({ children }: { children: React.ReactNode }) {
const [open, setOpen] = useState(false);
return (
<>
<button onClick={() => setOpen(true)}>Xem</button>
{open && <div role="dialog">{children}</div>}
</>
);
}
// app/page.tsx (Server)
import { Modal } from './_components/Modal';
import { ProductDetails } from './_components/ProductDetails'; // Server Component, query DB
export default function Page() {
return (
<Modal>
<ProductDetails id="p1" /> {/* render trên server, truyền xuống như dữ liệu */}
</Modal>
);
}
Mẫu này dùng khắp nơi: Tabs/Accordion/Carousel tương tác bọc nội dung render ở server.
server-only, client-only và biến môi trường
// lib/db.ts
import 'server-only'; // build lỗi ngay nếu file này bị import vào Client Component
export const db = new PrismaClient();
- Biến môi trường không có tiền tố
NEXT_PUBLIC_chỉ có ở server; nếu Client Component đọc, giá trị là chuỗi rỗng. NEXT_PUBLIC_*được nhúng cứng vào bundle lúc build — công khai, và đổi giá trị phải build lại.client-onlylàm điều ngược lại cho code chỉ dùng trên trình duyệt.
Context provider và thư viện bên thứ ba
// app/providers.tsx
'use client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ThemeProvider } from 'next-themes';
export function Providers({ children }: { children: React.ReactNode }) {
const [qc] = useState(() => new QueryClient()); // tạo theo từng request/phiên, không ở cấp module
return <QueryClientProvider client={qc}><ThemeProvider attribute="class">{children}</ThemeProvider></QueryClientProvider>;
}
// app/layout.tsx (Server)
<body><Providers>{children}</Providers></body> // children vẫn là Server Components
- Context không tồn tại trong Server Component. Provider phải là Client Component, đặt càng sâu càng tốt.
- Thư viện dùng hook mà chưa có
'use client'→ tạo file re-export:'use client'; export { Carousel } from 'acme-carousel';. - Dữ liệu dùng chung giữa nhiều Server Component trong một request: không cần context — gọi cùng hàm đã bọc
cache()của React (Module 5). - Store toàn cục (Zustand/Redux) ở cấp module trên server bị dùng chung giữa mọi request → tạo store trong Provider.
🚩 Sai lầm hay gặp
'use client'ở root layout 'cho chắc'.- Truyền nguyên bản ghi DB xuống Client Component.
- Import
lib/db.tstừ Client Component (không cóserver-onlythì có thể lọt cả driver DB vào bundle hoặc lỗi khó hiểu). - Dùng
windowngay khi render trong Client Component → lỗi khi SSR / hydration mismatch.
🏋️ Bài tập thực hành
Cho một trang sản phẩm viết hoàn toàn bằng 'use client' (fetch trong effect). Chuyển thành: page Server Component fetch dữ liệu, chỉ AddToCart, ImageGallery, ReviewForm là client; tab mô tả là Client Tabs bọc nội dung server qua children. Đo First Load JS trước/sau trong next build.
📚 Tài nguyên học tập
-
Next.js — Server and Client ComponentsHướng dẫn chính thứcDocs
-
react.dev — Server ComponentsĐặc tả phía ReactDocs
-
Dan Abramov — The Two ReactsMô hình tư duyBlog
✅ Tự đánh giá hoàn thành
- Tôi giải thích được
'use client'lan truyền theo import - Tôi biết loại props nào qua được ranh giới
- Tôi đặt được Server Component bên trong Client Component bằng children
- Tôi dùng
server-onlyvà hiểu rủi roNEXT_PUBLIC_ - Tôi đặt Provider đúng cách trong App Router