Open In App

ReactJS componentWillUnmount() Method

Last Updated : 18 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The componentWillUnmount() method allows us to execute the React code when the component gets destroyed or unmounted from the DOM (Document Object Model). This method is called during the Unmounting phase of the React Life-cycle i.e before the component gets unmounted.

All the cleanups such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount() should be coded in the componentWillUnmount() method block.

Tip: Never call setState() in componentWillUnmount() method.

Syntax:

componentWillUnmount()

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app functiondemo

Step 2: After creating your project folder i.e. functiondemo, move to it using the following command:

cd functiondemo

Project Structure: It will look like the following.

Project Structure

Example: In this example, we are going to build a name color application that changes the color of the text when the component is rendered in the DOM tree.

App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

Javascript




import React from 'react';
class ComponentOne extends React.Component {
 
  // Defining the componentWillUnmount method
  componentWillUnmount() {
    alert('The component is going to be unmounted');
  }
 
  render() {
    return <h1>Hello Geeks!</h1>;
  }
}
 
class App extends React.Component {
  state = { display: true };
  delete = () => {
    this.setState({ display: false });
  };
 
  render() {
    let comp;
    if (this.state.display) {
      comp = <ComponentOne />;
    }
    return (
      <div>
        {comp}
        <button onClick={this.delete}>
          Delete the component
        </button>
      </div>
    );
  }
}
 
export default App;


 
 Note: You can define your own styling in the App.css file.

Step to Run Application: Run the application using the following command from the root directory of the project: 

npm start

Output: 

 

 

Reference: https://reactjs.org/docs/react-component.html#componentwillunmount

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads