componentWillUnmount được gọi ngay trước khi component bị xóa khỏi DOM — đây là nơi bắt buộc phải cleanup để tránh memory leak.
Ví dụ: clearInterval(this.timerId), hủy WebSocket subscription, gọi controller.abort() để cancel fetch đang chạy. Không được gọi setState ở đây vì component không còn tồn tại. Tương đương hàm cleanup return () => clearInterval(id) trả về trong useEffect.
componentWillUnmount is called just before the component is removed from the DOM — this is where you must clean up to avoid memory leaks.
- Examples:
clearInterval(this.timerId), unsubscribing from a WebSocket, or callingcontroller.abort()to cancel an in-flight fetch. - Do not call setState here since the component no longer exists.
- The equivalent in function components is the cleanup function returned from useEffect:
return () => clearInterval(id).