Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre When to Use "use client" | Section
Building Web Apps with Next.js

bookWhen to Use "use client"

Glissez pour afficher le menu

By default, components in Next.js are server components. This means they run on the server and do not include client-side JavaScript.

However, some features require the component to run in the browser. In these cases, you need to use the "use client" directive.

Adding "use client" at the top of a file tells Next.js that this component should run on the client.

Example - Enabling Client Behavior

"use client";

import { useState } from "react";

export default function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      Count: {count}
    </button>
  );
}

This component uses state and handles user interaction, so it must run in the browser.

When You Need "use client"

You should use "use client" when your component needs browser-specific features.

This includes situations where you work with user interactions, such as clicks or form input, or when you use React hooks like useState and useEffect. It is also required when accessing browser APIs like window or localStorage.

If your component only displays data and does not require interaction, it should remain a server component.

Important Rule

Only use "use client" when necessary.

Client components include additional JavaScript in the browser, which can affect performance. Server components are more efficient and should be preferred whenever possible.

question mark

Which situation requires you to add the "use client" directive to a Next.js component file?

Sélectionnez la réponse correcte

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 1. Chapitre 18

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

Section 1. Chapitre 18
some-alt