ScanSkill

componentWillUnmount()

The componentWillUnmount() is called when a component is unmounted or removed from the DOM.

Syntax

The functions to be called when the components gets unmounted are stated inside componentWillUnmount().

  componentWillUnmount() {
    //functions here
  }

Example

class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = { show: true };
  }
  handleDelete = () => {
    console.log("delete")
    this.setState({ show: false });
  };
  render() {
    return (
      <div>
        {this.state.show && <Header />}
        <button type="button" onClick={this.handleDelete}>
          Delete Header
        </button>
      </div>
    );
  }
}

class Header extends React.Component {
  componentWillUnmount() {
    console.log("The component is about to be removed");
  }
  render() {
    return <h1>Hello World!</h1>;
  }
}
componentWillUnmount

Here, the header component is deleted and the console is displayed while unmounting the header component from the DOM.