Building Interactive Components in Next.js
メニューを表示するにはスワイプしてください
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.
フィードバックありがとうございます!
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください