Topic 19 of 39
Client Components
Overview
Client Components allow you to add interactivity to your application (hooks, state, event listeners, browser APIs). You explicitly opt into client rendering by adding the 'use client' directive at the top of a file.
Syntax
tsx
'use client'; // This directive defines the Client boundary
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicks: {count}
</button>
);
}Common Pitfalls
- Thinking Client Components only render on the client. They are actually pre-rendered on the server (HTML is generated) and then hydrated on the client.
- Putting
'use client'on every single file, destroying the performance benefits of Server Components.
Interview Questions
Q:
When should you use a Client Component?
A:
Use it when you need interactivity (onClick, onChange), React hooks (useState, useEffect), browser APIs (window, localStorage), or custom hooks that depend on state.
Real-World Example
A dark mode toggle button that relies on browser local storage.
example
tsx
'use client';
import { useState, useEffect } from 'react';
export default function ThemeToggle() {
const [theme, setTheme] = useState('light');
useEffect(() => {
// Accessing browser APIs
setTheme(localStorage.getItem('theme') || 'light');
}, []);
return <button onClick={/* toggle logic */}>Toggle Theme</button>;
}Check Your Knowledge
Test your understanding of Client Components with these quick questions.