Dark mode
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 ในสถานการณ์ต่างๆ
- โหลดข้อมูลครั้งแรก
jsx
// ใช้ useEffect สำหรับ Function Components
useEffect(() => {
// โค้ดทำงานหลัง render ครั้งแรก
fetchData();
}, []);
- ติดตามการเปลี่ยนแปลง
jsx
useEffect(() => {
// ทำงานเมื่อค่า props.userId เปลี่ยน
updateProfile();
}, [props.userId]);
- ทำความสะอาด
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 ที่เทียบเท่า
Method | Description |
---|---|
componentDidMount | เรียกหลัง render ครั้งแรก |
componentDidUpdate | เรียกหลังอัปเดต |
componentWillUnmount | เรียกก่อนคอมโพเนนต์ถูกทำลาย |
useEffect | ใช้ใน Function Components |
Class vs Function Components
ตารางเปรียบเทียบ lifecycle ระหว่าง Class และ Function Components
Class | Function (Hooks) | Description |
---|---|---|
componentDidMount | useEffect(() => {}, []) | หลัง render ครั้งแรก |
componentDidUpdate | useEffect(() => {}, [deps]) | เมื่อ dependencies เปลี่ยนแปลง |
componentWillUnmount | useEffect return function | ก่อน component ถูกทำลาย |
Common Pitfalls
ข้อผิดพลาดที่พบบ่อยเมื่อใช้งาน Lifecycle Hooks
- ลืมระบุ dependencies ใน useEffect
- Infinite loops จาก state ที่อัปเดตใน useEffect
- ลืม cleanup resources
Best Practices
แนวทางปฏิบัติที่ดีเมื่อใช้งาน Lifecycle Hooks
- แยก useEffect สำหรับ logic ที่ต่างกัน
- ใช้ dependency array ให้เหมาะสม
- ทำ cleanup ทุกครั้งที่สร้าง resources
- ใช้
componentDidMount
/useEffect
สำหรับโหลดข้อมูล - ทำความสะอาดใน
componentWillUnmount
- ระวัง infinite loop ใน
componentDidUpdate