What is a client component in Next.js and when should you use one?
Short answer
A client component is a piece of your app that runs in the browser and can use things like state, click handlers, and browser only APIs.
Advertisement
AModel answer
A client component is a piece of your app that runs in the browser and can use things like state, click handlers, and browser only APIs. You mark a file as a client component by adding a use client directive at the top, and you use them whenever your component needs interactivity that a server component cannot provide.
'use client';
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}Real-world example
A like button on a social media post needs to be a client component because it responds instantly to clicks and updates its own state in the browser without reloading the page.
Likely follow-ups
- Why do you need to write use client at the top of the file?
- Can a client component also fetch data from an API?
Related topics