'use client' đặt ở đầu file để đánh dấu component là Client Component.
- Cần thiết khi component dùng: useState, useEffect, event handlers, browser APIs.
- Đặt boundary tại component cần interactivity, không cần wrap toàn app.
tsx
// components/like-button.tsx
'use client' // ← bắt buộc vì dùng useState và onClick
import { useState } from 'react'
export function LikeButton({ initialCount }: { initialCount: number }) {
const [count, setCount] = useState(initialCount)
return (
<button onClick={() => setCount(c => c + 1)}>
❤️ {count}
</button>
)
}
// app/post/page.tsx — Server Component, không cần 'use client'
import { LikeButton } from '@/components/like-button'
export default async function PostPage() {
const post = await fetchPost()
return (
<article>
<h1>{post.title}</h1>
{/* Server Component chứa Client Component — OK */}
<LikeButton initialCount={post.likes} />
</article>
)
}