Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Aprenda Building Interactive Components in Next.js | Section
/
Building Web Apps with Next.js

bookBuilding Interactive Components in Next.js

Deslize para mostrar o menu

So far, many of the components in this course have focused on rendering content. However, real applications also need interaction. Users click buttons, type into inputs, open menus, and update values on the screen.

In Next.js, interactive behavior is built with Client Components. Since pages and layouts are Server Components by default, you add interactivity by creating a component that runs in the browser and marking it with "use client". Client Components are the right choice when you need state, event handlers, lifecycle logic, custom hooks, or browser APIs.

Example - Interactive Counter

"use client";

import { useState } from "react";

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

  return (
    <div>
      <p>Current count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increase</button>
    </div>
  );
}

This component is interactive because it uses useState and responds to a button click. Without "use client", this code would not work as expected in the App Router model. The directive must be placed at the top of the file before imports, and it defines the client-server boundary for that file.

Using the Interactive Component Inside a Page

import Counter from "./Counter";

export default function Page() {
  return (
    <main>
      <h1>Dashboard</h1>
      <Counter />
    </main>
  );
}

Here, the page can stay a Server Component while the counter handles interaction in the browser. This is the normal pattern in modern Next.js: keep as much of the UI as possible on the server, and add Client Components only where interactivity is needed.

Why This Matters

Interactive components let users do more than just read content. They make it possible to build forms, tabs, filters, counters, modals, and many other common UI patterns. At the same time, Next.js encourages you to keep only the interactive parts on the client, which helps reduce unnecessary JavaScript sent to the browser.

question mark

Which type of component is required to make the button interactive as shown in the example above?

Selecione a resposta correta

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 1. Capítulo 19

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

Seção 1. Capítulo 19
some-alt