Topic 50 of 54
The 'use client' Directive
Overview
If Server Components are the default in modern frameworks (like Next.js), how do you add interactivity? How do you use state? You must explicitly tell React that a specific component needs to run in the browser. You do this by placing the `'use client'` directive at the very top of the file. This creates a boundary: everything below it becomes part of the client JS bundle.
Syntax
The `'use client'` directive tells the bundler to include this component (and any components it imports) in the JavaScript payload sent to the browser.
Adding Interactivity
jsx
// Must be the very first line of code
'use client';
import { useState } from 'react';
export default function LikeButton({ initialLikes }) {
// We can use hooks again because this is a Client Component!
const [likes, setLikes] = useState(initialLikes);
return (
<button onClick={() => setLikes(l => l + 1)}>
❤️ {likes}
</button>
);
}Common Pitfalls
- Putting `'use client'` at the top of your `layout.jsx` or root component. This forces your ENTIRE app to become client-side, completely destroying the benefits of React Server Components.
Interview Tips
- A common architectural pattern: 'Leaves should be clients'. Keep your Server Components high up in the tree for layout and data, and only use `'use client'` on the specific small components (like buttons or forms) at the 'leaves' of the tree.
Real-World Example
Passing data from a Server Component to a Client Component.
example
jsx
// ServerComponent.jsx (Server)
import LikeButton from './LikeButton'; // Client Component
export default async function BlogPost() {
const post = await db.getPost(1);
return (
<article>
<h1>{post.title}</h1>
{/* We pass the server data to the client component as a prop */}
<LikeButton initialLikes={post.likes} />
</article>
);
}