reactjs – React Component Lifecycle – Component Removal

componentWillUnmount()

This method is called before a component is unmounted from the DOM.

It is a good place to perform cleaning operations like:

  • Removing event listeners.
  • Clearing timers.
  • Stopping sockets.
  • Cleaning up redux states.
componentWillUnmount(){
  ...
}

An example of removing attached event listener in componentWillUnMount

import React, { Component } from 'react';

export default class SideMenu extends Component {

  constructor(props) {
    super(props);
    this.state = {
        ...
      };
    this.openMenu = this.openMenu.bind(this);
    this.closeMenu = this.closeMenu.bind(this);
  }

  componentDidMount() {
    document.addEventListener("click", this.closeMenu);
  }

  componentWillUnmount() {
    document.removeEventListener("click", this.closeMenu);
  }

  openMenu() {
    ...
  }

  closeMenu() {
    ...
  }

  render() {
    return (
      <div>
        <a
          href      = "javascript:void(0)"
          className = "closebtn"
          onClick   = {this.closeMenu}
        >
          ×
        </a>
        <div>
          Some other structure
        </div>
      </div>
    );
  }
}

if you want to reproduce, please indicate the source:
reactjs – React Component Lifecycle – Component Removal - CodeDay