Skip to content
Grok

React Lifecycle Hooks (วงจรชีวิตของคอมโพเนนต์)

Lifecycle Hooks

Lifecycle Hooks ใน React คือวิธีการจัดการการทำงานของคอมโพเนนต์ในแต่ละช่วงชีวิต ตั้งแต่การสร้างจนถึงการทำลาย

Hookช่วงการทำงานตัวอย่างการใช้งาน
componentDidMountหลังแสดงผลโหลดข้อมูลจาก API
componentDidUpdateหลังอัปเดตปรับ UI ตามข้อมูลใหม่
componentWillUnmountก่อนถอดออกล้าง timer/event listeners
useEffectทดแทนทุกช่วงจัดการ side effects

useEffect (การจัดการ side effects)

Hook หลักที่ใช้จัดการ side effects ใน Function Components สามารถทดแทน lifecycle methods ของ Class Components ได้

jsx
import { useEffect } from "react";

function MyComponent() {
  useEffect(() => {
    // ทำงานหลังแสดงผล (เหมือน componentDidMount)
    console.log("แสดงผลแล้ว");

    return () => {
      // ทำงานก่อนถอดออก (เหมือน componentWillUnmount)
      console.log("เตรียมถอดออก");
    };
  }, []); // dependencies array
}

Class Component Lifecycle (สำหรับ Legacy Code)

วิธีการจัดการ lifecycle แบบดั้งเดิมด้วย Class Components ที่ยังคงพบเห็นในโค้ดเก่า

jsx
class MyComponent extends React.Component {
  componentDidMount() {
    // ทำงานหลังแสดงผล
    console.log("แสดงผลแล้ว");
  }

  componentWillUnmount() {
    // ทำงานก่อนถอดออก
    console.log("เตรียมถอดออก");
  }
}

คำอธิบายภาษาไทย

Lifecycle คืออะไร

วงจรชีวิตของคอมโพเนนต์ React ที่แบ่งเป็น 3 ช่วงหลัก: Mounting, Updating, และ Unmounting

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

วิธีใช้ในทางปฏิบัติ

ตัวอย่างการใช้งาน Lifecycle Hooks ในสถานการณ์ต่างๆ

  1. โหลดข้อมูลครั้งแรก
jsx
// ใช้ useEffect สำหรับ Function Components
useEffect(() => {
  // โค้ดทำงานหลัง render ครั้งแรก
  fetchData();
}, []);
  1. ติดตามการเปลี่ยนแปลง
jsx
useEffect(() => {
  // ทำงานเมื่อค่า props.userId เปลี่ยน
  updateProfile();
}, [props.userId]);
  1. ทำความสะอาด
jsx
useEffect(() => {
  const timer = setInterval(() => {}, 1000);

  return () => {
    // ทำงานก่อนคอมโพเนนต์ถูกทำลาย
    clearInterval(timer);
  };
}, []);

ข้อควรระวัง

สิ่งที่ต้องระมัดระวังเมื่อใช้งาน Lifecycle Hooks

  • ⚠️ อย่าลืมใส่ dependencies ใน [] ของ useEffect
  • ⚠️ ระวัง infinite loop เมื่ออัปเดต state ใน useEffect
  • ✅ ควรแยก useEffect สำหรับงานแต่ละประเภท

Practical Examples

Fetching Data with Dependencies

ตัวอย่างการโหลดข้อมูลด้วยการระบุ dependencies

jsx
import { useEffect, useState } from "react";

function UserProfile({ userId }) {
  const [user, setUser] = useState(null);

  useEffect(() => {
    const fetchUser = async () => {
      const response = await fetch(`/api/users/${userId}`);
      setUser(await response.json());
    };

    fetchUser();
  }, [userId]); // Re-run when userId changes
}

Cleanup Example

ตัวอย่างการทำความสะอาด resources ก่อนคอมโพเนนต์ถูกทำลาย

jsx
useEffect(() => {
  const timer = setInterval(() => {
    console.log("Timer tick");
  }, 1000);

  return () => {
    clearInterval(timer);
    console.log("Timer cleared");
  };
}, []);

Key Lifecycle Methods

ตารางสรุป methods สำคัญใน Class Components และ Hooks ที่เทียบเท่า

MethodDescription
componentDidMountเรียกหลัง render ครั้งแรก
componentDidUpdateเรียกหลังอัปเดต
componentWillUnmountเรียกก่อนคอมโพเนนต์ถูกทำลาย
useEffectใช้ใน Function Components

Class vs Function Components

ตารางเปรียบเทียบ lifecycle ระหว่าง Class และ Function Components

ClassFunction (Hooks)Description
componentDidMountuseEffect(() => {}, [])หลัง render ครั้งแรก
componentDidUpdateuseEffect(() => {}, [deps])เมื่อ dependencies เปลี่ยนแปลง
componentWillUnmountuseEffect return functionก่อน component ถูกทำลาย

Common Pitfalls

ข้อผิดพลาดที่พบบ่อยเมื่อใช้งาน Lifecycle Hooks

  1. ลืมระบุ dependencies ใน useEffect
  2. Infinite loops จาก state ที่อัปเดตใน useEffect
  3. ลืม cleanup resources

Best Practices

แนวทางปฏิบัติที่ดีเมื่อใช้งาน Lifecycle Hooks

  • แยก useEffect สำหรับ logic ที่ต่างกัน
  • ใช้ dependency array ให้เหมาะสม
  • ทำ cleanup ทุกครั้งที่สร้าง resources
  • ใช้ componentDidMount/useEffect สำหรับโหลดข้อมูล
  • ทำความสะอาดใน componentWillUnmount
  • ระวัง infinite loop ใน componentDidUpdate