How to Use the React componentWillUnmount() Method

09/28/2021

Contents

In this article, you will learn how to use the React componentWillUnmount() method.

Using the componentWillUnmount() method

The componentWillUnmount() method is a lifecycle method in React that is called just before a component is removed from the DOM (Document Object Model). It is used to perform any cleanup operations that may be necessary, such as removing event listeners, cancelling timers, or resetting any state that may have been set during the component’s lifecycle.

Here’s how you can use the componentWillUnmount() method in your React component:

Define the method

In your React component class, define the componentWillUnmount() method. This method will be called automatically by React when the component is about to be removed from the DOM.

class MyComponent extends React.Component {
  componentWillUnmount() {
    // Perform any cleanup operations here
  }

  // Rest of your component code goes here
}

Add cleanup code

Within the componentWillUnmount() method, add any code that needs to be executed before the component is unmounted. This could include removing event listeners, cancelling timers, or resetting any state that may have been set during the component’s lifecycle.

class MyComponent extends React.Component {
  componentDidMount() {
    this.interval = setInterval(() => {
      // Do something every second
    }, 1000);
  }

  componentWillUnmount() {
    clearInterval(this.interval);
  }

  render() {
    // Render your component's UI here
  }
}

In the example above, we have a component that sets up an interval when it mounts using setInterval(). We need to remove this interval when the component unmounts, so we use the componentWillUnmount() method to clear it using clearInterval().

Remember to remove any event listeners

If your component adds any event listeners during its lifecycle, make sure to remove them in the componentWillUnmount() method. This will prevent memory leaks and ensure that your application runs smoothly.

class MyComponent extends React.Component {
  componentDidMount() {
    document.addEventListener('click', this.handleClick);
  }

  componentWillUnmount() {
    document.removeEventListener('click', this.handleClick);
  }

  handleClick = () => {
    // Handle click events here
  }

  render() {
    // Render your component's UI here
  }
}

In the example above, we add a click event listener to the document in componentDidMount(). We need to remove this listener when the component unmounts, so we use the componentWillUnmount() method to remove it using removeEventListener().