React componentWillUnmount() Method
The componentWillUnmount() method is formatted as follows:
componentWillUnmount()
The componentWillUnmount() method is invoked immediately before a component is unmounted and destroyed.
The setState() method should not be called within componentWillUnmount(), as the component will never re-render. Once a component instance is unmounted, it will never be mounted again.
In the following example, the componentWillUnmount()
method is called when the component is about to be removed from the DOM:
Example
class Container extends React.Component {
constructor(props) {
super(props);
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader;
if (this.state.show) {
myheader = <Child />;
};
return (
<div>
{myheader}
<button type="button" onClick={this.delHeader}>Delete Header Component</button>
</div>
);
}
}
class Child extends React.Component {
componentWillUnmount() {
alert("The header component is about to be unmounted.");
}
render() {
return (
<h1>Hello tutorialpro!</h1>
);
}
}
ReactDOM.render(<Container />, document.getElementById('root'));