🎓 A1Learner
🔍
0 of 50 lessons completed

Next.js "use client"

"use client" is one line at the top of a file. It moves that component to the browser.

The mark-read button

The button holds its own read flag. A click flips it, and the label changes.

'use client';

import { useState } from "react";

export default function MarkReadButton({ read }: { read: boolean }) {
  const [isRead, setIsRead] = useState(read);
  return (
    <button onClick={() => setIsRead(!isRead)}>
      {isRead ? "Read" : "Mark as read"}
    </button>
  );
}

A component without the line

This counter uses useState but has no "use client" line. It cannot run as written in a server page.

import { useState } from "react";

export default function BrokenCounter() {
  const [count, setCount] = useState(0);
  return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}

Example

curl -s http://localhost:3111/ | grep -o 'Mark as read\|>Read<' | sort | uniq -c

Key points

  • "use client": the line that marks a component as a Client Component
  • A Client Component runs in the browser. It can hold state and answer clicks.
  • useState: the React hook that holds a value that can change
  • Clicks, typing, and browser tools all need a Client Component.
  • The line goes at the very top of the file, above the imports.
  • Only the file that carries the line moves. The rest of the page stays on the server.

In this example, the check reads the home page and counts the button labels. Three buttons say Mark as read, for the three unread books. Two buttons say Read, for the two books already read. The labels come from the MarkReadButton component, which is a Client Component. The click that flips a label runs in the browser, so curl shows the labels but cannot show the click itself.

Note

A click needs a browser, so a button that changes on click must be a Client Component.

Try it Yourself

Edit the code, then press Run.

Running is simulated · TypeScript Playground

Exercise

Where does the "use client" line go?