ReactJS – componentWillUnmount() Method


In this article, we are going to see how to execute a function when the component is deleted from the DOM tree.

This method is called during the unmounting phase of the React Lifecycle, i.e., before the component is destroyed or unmounted from the DOM tree. This method is majorly used to cancel all the subscriptions that were previously created in the componentWillMount method.

Never call this.setState() inside the componentWillUnmount method as this component is never going to be re-rendered again.

Syntax

componentWillUnmount()

Example

In this example, we will build a React application which displays the list of all users. On clicking the 'Delete User' button, the User component will get unmounted from the DOM tree and before destroying the User component, the componentWillUnmount method will be called.

Our first component in the following example is App. This component is the parent of the Change component. We are creating Change separately and just adding it inside the JSX tree in our App component. Hence, only the App component needs to be exported.

App.jsx

import React from 'react';

class App extends React.Component {
   constructor() {
      super();
      this.state = {
         delete: false,
      };
   }
   render() {
      return (
         <div>
            <h1>User List</h1>
            <button onClick={() => this.setState({ delete: true })}>
               Delete Users
            </button>
            {this.state.delete ? null : <User />}
         </div>
      );
   }
}
class User extends React.Component {
   componentWillUnmount() {
      alert('Deleted User successfully');
   }
   render() {
      return (
         <div>
            <h3>Username: Rahul</h3>
            <h3>Email: rbbansal558@gmail.com</h3>
         </div>
      );
   }
}
export default App;

Output

This will produce the following result.

Updated on: 18-Mar-2021

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements