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

bookWhen to Use "use client"

Svep för att visa menyn

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?

Vänligen välj det korrekta svaret

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 1. Kapitel 18

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

Avsnitt 1. Kapitel 18
some-alt