Client Components
Add "use client" at the top of a file to run it in the browser with state, effects, and event handlers.
Syntax
'use client'; // first line of the fileA Client Component runs in the browser and can use everything React offers on the client: useState, useEffect, event handlers like onClick, and browser APIs. You opt in by adding the "use client" directive as the very first line of the file.
When you need one
- Interactive widgets (counters, toggles, tabs).
- Forms with live validation.
- Anything using
useState,useEffect, or the DOM.
Example
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}When to use it
- A counter widget needs useState so it is marked 'use client' to run interactivity in the browser.
- A search input that filters a list on each keystroke becomes a Client Component because it uses onChange events.
- A theme toggle that reads localStorage must be a Client Component since localStorage is browser-only.
More examples
Counter with useState
Adding 'use client' at the top makes React hooks and browser events available in the component.
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}Controlled search input
Controlled inputs require state on every keystroke, making this a natural Client Component.
'use client';
import { useState } from 'react';
export default function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
const [query, setQuery] = useState('');
return (
<input
value={query}
onChange={e => { setQuery(e.target.value); onSearch(e.target.value); }}
placeholder="Search..."
/>
);
}useEffect for side effects
useEffect and browser APIs like window require 'use client' because they only exist in the browser.
'use client';
import { useEffect, useState } from 'react';
export default function WindowWidth() {
const [width, setWidth] = useState(0);
useEffect(() => {
setWidth(window.innerWidth);
const handler = () => setWidth(window.innerWidth);
window.addEventListener('resize', handler);
return () => window.removeEventListener('resize', handler);
}, []);
return <p>Window width: {width}px</p>;
}
Discussion