0Pricing
Next.js 15 Fullstack Web Apps · บทเรียน

คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ

เรียนรู้ว่าเมื่อใดและอย่างไรจึงควรใช้คอมโพเนนต์ไคลเอ็นต์สำหรับองค์ประกอบส่วนติดต่อผู้ใช้แบบโต้ตอบที่ต้องใช้สถานะฝั่งไคลเอ็นต์

คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ เป็นบทเรียน Next.js 15 Fullstack Web Apps ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Next.js 15 Fullstack Web Apps และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Meet Client Components

Welcome to Client Components! In Next.js with the App Router, components are Server Components by default. But sometimes, you need interactivity directly in the browser.

Client Components are special components that run on the client-side, meaning in the user's web browser. They are essential for adding dynamic features to your application.

Server vs. Client: A Quick Look

Let's quickly recap: Server Components render on the server, ideal for static content, data fetching, and reducing client-side JavaScript.

Client Components, on the other hand, allow for:

  • User interaction (clicks, input changes)
  • Managing state with React Hooks (useState, useEffect)
  • Accessing browser-specific APIs (localStorage, window)

They bring your UI to life!

Why Use Client Components?

You should reach for a Client Component when your UI needs to be interactive. Think about common web features:

  • Counters & Toggles: Any UI element that changes based on user input.
  • Forms: Input fields, validation, and submission logic.
  • Animations: Client-side animations and transitions.
  • Real-time Updates: Components that respond to WebSocket events.
  • Browser-specific Logic: Anything that directly manipulates the DOM or uses browser APIs.

The 'use client' Directive

To tell Next.js that a component should be a Client Component, you simply add the "use client" directive at the very top of the file, before any imports.

This directive is crucial! It marks the boundary between server-side and client-side code. Everything below it (including imported modules) will be treated as part of the client bundle.

Building an Interactive Counter

Here's a classic example: a simple counter. Notice the "use client" directive and the use of React's useState Hook to manage the count.

The button's onClick handler updates the state, triggering a re-render in the browser.

    "use client";
    import React, { useState } from 'react';

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

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

Handling More Interactions

Beyond simple clicks, Client Components excel at managing input from users. Here's an example using an input field to mirror text as you type.

The onChange event handler updates the component's state every time the input value changes.

    "use client";
    import React, { useState } from 'react';

    export default function InputMirror() {
      const [text, setText] = useState('');

      return (
        <div>
          <input
            type="text"
            value={text}
            onChange={(e) => setText(e.target.value)}
            placeholder="Type here..."
          />
          <p>You typed: {text}</p>
        </div>
      );
    }

Client-Side Effects with useEffect

The useEffect Hook is your go-to for side effects that need to run in the browser, like setting up timers, fetching data on component mount, or subscribing to external events.

This timer component uses useEffect to update its seconds state every second.

    "use client";
    import React, { useState, useEffect } from 'react';

    export default function Timer() {
      const [seconds, setSeconds] = useState(0);

      useEffect(() => {
        const interval = setInterval(() => {
          setSeconds(prev => prev + 1);
        }, 1000);
        return () => clearInterval(interval); // Cleanup function
      }, []); // Empty dependency array means run once on mount

      return (
        <p>Timer: {seconds} seconds</p>
      );
    }

Accessing Browser Features

Since Client Components run in the browser, they have full access to browser-specific APIs and global objects like window and localStorage.

This example shows how to read from and write to localStorage, which is unavailable in Server Components.

    "use client";
    import React, { useState, useEffect } from 'react';

    export default function LocalStorageDisplay() {
      const [storedValue, setStoredValue] = useState('');

      useEffect(() => {
        // This code runs only on the client after hydration
        const item = localStorage.getItem('myKey');
        if (item) {
          setStoredValue(item);
        }
      }, []);

      const saveValue = () => {
        localStorage.setItem('myKey', 'Hello from CoddyKit!');
        setStoredValue('Hello from CoddyKit!');
      };

      return (
        <div>
          <p>Stored: {storedValue || 'Nothing yet!'}</p>
          <button onClick={saveValue}>
            Save to LocalStorage
          </button>
        </div>
      );
    }

Nesting Client Components

You can nest Client Components within other Client Components, and even within Server Components. A Server Component can render a Client Component as a child.

When a Server Component renders a Client Component, the Client Component's JavaScript is sent to the browser, and it 'hydrates' (becomes interactive) once loaded.

This allows you to build complex UIs where static parts are server-rendered, and interactive parts are client-rendered.

Client Component Check

Time to test your understanding of Client Components!

Client Components: Key Takeaways

You've mastered the basics of Client Components!

  • They are marked with "use client" at the top of the file.
  • Essential for interactivity, state management with Hooks (useState, useEffect), and event handling.
  • They can access browser-specific APIs (e.g., localStorage, window).
  • Server Components can render Client Components, allowing for a mix of server and client rendering.

Next, we'll explore more advanced data fetching patterns, leveraging both Server and Client Components effectively!

คำถามที่พบบ่อย

บทเรียน “คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Next.js 15 Fullstack Web Apps ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Next.js 15 Fullstack Web Apps มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ”

เรียนรู้ว่าเมื่อใดและอย่างไรจึงควรใช้คอมโพเนนต์ไคลเอ็นต์สำหรับองค์ประกอบส่วนติดต่อผู้ใช้แบบโต้ตอบที่ต้องใช้สถานะฝั่งไคลเอ็นต์ คุณปฏิบัติ Next.js 15 Fullstack Web Apps ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Next.js 15 Fullstack Web Apps หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Next.js 15 Fullstack Web Apps บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Next.js 15 Fullstack Web Apps นี้ได้ไหม

ได้ บทเรียน Next.js 15 Fullstack Web Apps ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. เจาะลึกคอมโพเนนต์เซิร์ฟเวอร์
  2. คอมโพเนนต์ไคลเอ็นต์และการโต้ตอบ
  3. รูปแบบการดึงข้อมูลขั้นสูง
  4. การแคช การตรวจสอบใหม่ และการสตรีม
← กลับไปที่ Next.js 15 Fullstack Web Apps