Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Вивчайте When to Use "use client" | Section
Практика
Проекти
Вікторини та виклики
Вікторини
Виклики
/
Building Web Apps with Next.js

bookWhen to Use "use client"

Свайпніть щоб показати меню

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?

Виберіть правильну відповідь

Все було зрозуміло?

Як ми можемо покращити це?

Дякуємо за ваш відгук!

Секція 1. Розділ 18

Запитати АІ

expand

Запитати АІ

ChatGPT

Запитайте про що завгодно або спробуйте одне із запропонованих запитань, щоб почати наш чат

Секція 1. Розділ 18
some-alt