| name | nextjs-client-component |
| description | null |
Client Component
Category: nextjs · Status: 🟢 Active
When to use
Khi cần state, event handler, hook, hoặc browser API → thêm 'use client'.
Steps
- Đặt
'use client' ở dòng đầu file khi cần useState/useEffect/onClick.
- Giữ client component nhỏ, đặt ở "lá" của cây để giảm JS gửi xuống.
- Nhận data từ Server Component qua props thay vì fetch lại.
- Không bọc cả trang trong 'use client'; chỉ phần tương tác.
- Có thể nhận
children là Server Component để giữ phần tĩnh ở server.
Template
'use client';
import { useState } from 'react';
export function Counter({ initial }: { initial: number }) {
const [count, setCount] = useState(initial);
return <button onClick={() => setCount((c) => c + 1)}>{count}</button>;
}
Example
Good: Button/counter nhỏ ở lá, nhận initial từ server qua props.
Avoid: 'use client' ở layout gốc, fetch lại data đã có ở server.
Checklist