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.
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:
Project Structure: It will look like the following.
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.
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: