From the official tutorial:
componentWillUnmount()is invoked immediately before a component is unmounted and destroyed. Perform any nece
In this simple example (example taken from React Docs) I am using it for clearing interval of a Clock component.
For example in your page you have 2 tabs, one of them is showing User Info and second tab is User Schedule which shows a live clock over there. Once you switch to User Schedule tab, componentDidMount will be called to set the timer. And once you switch back to User Info, there is no need to keep this interval hook and you can write your unbind/unsubscribe logic in componentWillUnmount event.
import React from "react";
export default class Clock extends React.Component {
constructor(props) {
console.log("Clock", "constructor");
super(props);
this.state = {
date: new Date()
};
}
tick() {
this.setState({
date: new Date()
});
}
// These methods are called "lifecycle hooks".
componentDidMount() {
console.log("Clock", "componentDidMount");
this.timerID = setInterval(() => {
this.tick();
}, 1000);
}
// These methods are called "lifecycle hooks".
componentWillUnmount() {
console.log("Clock", "componentWillUnmount");
clearInterval(this.timerID);
}
render() {
return (
It is {this.state.date.toLocaleTimeString()}.
);
}
}