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

bookBuilding Interactive Components in Next.js

Swipe um das Menü anzuzeigen

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?

Wählen Sie die richtige Antwort aus

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 1. Kapitel 19

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Abschnitt 1. Kapitel 19
some-alt