ComponentWillUnmount

Pascual Vila
Frontend Instructor.
componentWillUnmount is a lifecycle method of class components in React. It runs before the component is removed from the DOM. It is useful for cleaning up subscriptions or canceling background tasks such as API requests or intervals.
Example of componentWillUnmount:
{`import React, { Component } from "react";
class Clock extends Component {
constructor(props) {
super(props);
this.state = { time: new Date().toLocaleTimeString() };
}
componentDidMount() {
this.intervalId = setInterval(() => {
this.setState({ time: new Date().toLocaleTimeString() });
}, 1000);
}
componentWillUnmount() {
clearInterval(this.intervalId);
}
render() {
return <h1>{this.state.time}</h1>;
}
}
export default Clock;`}