Topic 28 of 47
Client Components Directive ("use client")
Overview
The 'use client' directive marks a boundary between the server and the client. Components with this directive become Client Components, meaning they are hydrated in the browser and can use state, effects, and browser APIs.
Syntax
tsx
// app/components/Counter.tsx
'use client'; // Must be at the very top of the file
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Common Pitfalls
- Client Components are still pre-rendered on the server (SSR) for the initial HTML, then hydrated. They do not mean 'Browser Only'.
- If you import a Server Component into a Client Component directly, it becomes a Client Component. Pass Server Components as 'children' or props to maintain their server nature.
Real-World Example
Using browser APIs like window and localStorage in a Client Component:
example
tsx
// app/components/ThemeToggle.tsx
'use client';
import { useEffect, useState } from 'react';
export default function ThemeToggle() {
const [theme, setTheme] = useState('light');
useEffect(() => {
// Accessing browser APIs is safe here
const saved = localStorage.getItem('theme');
if (saved) setTheme(saved);
}, []);
return (
<button onClick={() => localStorage.setItem('theme', theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
);
}