Next.js › Client Components & Hydration

What is a client component in Next.js and when should you use one?

Beginner

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.

Common 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?