Step to Create a 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
Example: Write the following code in App.js file
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; |
Start your application using the following command.
npm start
Output:
Explain the purpose of the componentWillUnmount() method?
Every React Component has a lifecycle of its own, the lifecycle of a component can be defined as the series of methods invoked in different stages of the component’s existence. Mounting and Unmounting refer to key lifecycle phases that occur during creating and removing components or elements in a web application. In this article, we will learn the purpose of the componentWillUnmount() method.
Syntax of componentWillUnmount Method:
componentWillMount() {
// Perform the required
// activity inside it
}
Contact Us