3 ระยะของ React Lifecycle
- Mounting: Component ถูกสร้างและ Render เข้า DOM ครั้งแรก
- Updating: State หรือ Props เปลี่ยนแปลง Component Re-render
- Unmounting: Component ถูกลบออกจาก DOM
Lifecycle Methods สำคัญใน Class Component
Mounting Phase
constructor(props)- ตั้งค่า Initial State (Optional)render()- **จำเป็น** คืนค่า JSX เพื่อ RendercomponentWillMount()- รันก่อน Mount (Legacy, ควรใช้ constructor หรือ useEffect แทน)
Updating Phase
render()- เรียกใหม่เมื่อ State/Props เปลี่ยนcomponentDidUpdate()- หลัง Update เสร็จ (Optional)
Unmounting Phase
componentWillUnmount()- ทำความสะอาด (Cleanup) ก่อน Unmount (Optional)
ตัวอย่าง: User Login/Logout Flow
class UserContainer extends React.Component {
constructor(props) {
super(props);
this.state = { currentUser: "" };
}
componentWillMount() {
this.setState({ currentUser: "John" }); // Login
}
logout = () => {
this.setState({ currentUser: "" }); // Logout
}
render() {
if (this.state.currentUser === "John") {
return (
<UserProfile />
<button onClick={this.logout}>Logout</button>
);
} else {
return <button>Login</button>;
}
}
}
class UserProfile extends React.Component {
componentWillUnmount() {
alert("Logged Out"); // Cleanup
}
render() {
return <h1>Welcome back, John!</h1>;
}
}
สรุป
เข้าใจ Lifecycle ช่วยควบคุมพฤติกรรม Component ได้แม่นยำ ปัจจุบันแนะนำให้ใช้ **Hooks (useEffect)** แทน Lifecycle Methods ใน Class Component เพราะเขียนง่ายและทันสมัยกว่า