บทที่ 7: React Hooks (useState & useEffect)

เรียนรู้การใช้งาน React Hooks สำหรับจัดการ state และ side effects ใน Next.js 15
วัตถุประสงค์การเรียนรู้

เข้าใจการใช้ useState สำหรับจัดการ state

เข้าใจการใช้ useEffect สำหรับ side effects

เรียนรู้ dependency arrays และการ cleanup

สร้าง interactive components ด้วย hooks

🤔 React Hooks คืออะไร?

React Hooks คือ functions พิเศษที่ให้เราใช้ React features ต่างๆ ได้ใน functional components เช่น state management, lifecycle methods, และอื่นๆ โดยไม่ต้องเขียน class components

useState

จัดการ state ใน functional components ได้ง่ายและมีประสิทธิภาพ

useEffect

จัดการ side effects เช่น API calls, subscriptions, cleanup

Dependency Array

ควบคุมการ re-run ของ effects ด้วย dependency array

Performance

Optimize การ render และ prevent unnecessary updates

📦 useState Hook

useState เป็น Hook สำหรับจัดการ state ใน functional components ช่วยให้เราสามารถเก็บและอัพเดตข้อมูลได้

'use client';
import { useState } from 'react';

export default function Counter() {
  // ประกาศ state variable ชื่อ 'count' เริ่มต้นที่ 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <h2>Count: {count}</h2>
      <button onClick={() => setCount(count + 1)}>
        เพิ่ม
      </button>
      <button onClick={() => setCount(count - 1)}>
        ลด
      </button>
      <button onClick={() => setCount(0)}>
        รีเซ็ต
      </button>
    </div>
  );
}

⚡ useEffect Hook

useEffect เป็น Hook สำหรับจัดการ side effects เช่น API calls, subscriptions, หรือการเปลี่ยนแปลง DOM หลังจากที่ component render

🔄 Run Every Render
useEffect(() => {
  console.log('Rendered');
});
🎬 Run Once (Mount)
useEffect(() => {
  fetchData();
}, []); // empty dependency
👀 Watch Dependencies
useEffect(() => {
  updateTitle(count);
}, [count]); // watch count
🧹 Cleanup Function
useEffect(() => {
  const timer = setInterval(...);
  return () => clearInterval(timer);
}, []);
📡 Fetch Demo
💡 Best Practices สำหรับ React Hooks

ใช้ TypeScript

กำหนด types สำหรับ state และ props เพื่อ type safety

แยก state ให้เหมาะสม

ไม่ควรรวม state ที่ไม่เกี่ยวข้องกันในตัวแปรเดียว

ระวัง dependency arrays

ใส่ dependencies ครบถ้วนเพื่อป้องกัน bugs

ทำ cleanup เสมอ

cleanup intervals, event listeners, subscriptions

สร้าง Custom Hooks

แยก logic ที่ใช้ซ้ำออกมาเป็น custom hooks

ใช้ 'use client' ใน Next.js 15

ระบุ Client Components เมื่อใช้ hooks

🎯 ยินดีด้วย! คุณเรียนจบบทที่ 7 แล้ว

ตอนนี้คุณสามารถใช้ useState และ useEffect เพื่อสร้าง interactive components ได้แล้ว พร้อมสำหรับการเรียนรู้ Zod Validation ในบทถัดไป