Friday, November 29, 2024
Google search engine
HomeLanguagesExplain the meaning of Mounting and Demounting

Explain the meaning of Mounting and Demounting

We have seen so far that React web apps are actually a collection of independent components that run according to the interactions made with them. Every React Component has a lifecycle of its own, lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. The definition is pretty straightforward but what do we mean by different stages? A React Component can go through four stages of its life as follows.

  • Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.
  • Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.
  • Updating: Updating is the stage when the state of a component is updated and the application is repainted.
  • Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.
Here we will learn about Mounting and Demounting/Unmounting in Detail

Mounting: Mounting is the phase of the component lifecycle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time on the webpage. Now React follows a default procedure in the Naming Conventions of these predefined functions where the functions containing “Will” represents before some specific phase and “Did” represents after the completion of that phase. The mounting phase consists of two such predefined functions as described below.

componentWillMount() Function: As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time.

App.js




import React from "react";
  
class ComponentOne extends React.Component {
  UNSAFE_componentWillMount() {
    console.log("Component is mounted in the DOM");
  }
  render() {
    return <h1>Hello Geeks!</h1>;
  }
}
  
class App extends React.Component {
  render() {
    return (
      <div>
        <ComponentOne />
      </div>
    );
  }
}
  
export default App;


Mounting

componentDidMount() Function: Similarly as the previous one this function is invoked right after the component is mounted on the DOM i.e. this function gets invoked once after the render() function is executed for the first time

App.js




import React from "react";
class App extends React.Component {
  constructor(props) {
    super(props);
  
    // Initializing the state
    this.state = { color: "lightgreen" };
  }
  componentDidMount() {
      
    // Changing the state after 2 sec
    // from the time when the component
    // is rendered
    setTimeout(() => {
      this.setState({ color: "wheat" });
    }, 2000);
  }
  render() {
    return (
      <div>
        <p
          style={{
            color: this.state.color,
            backgroundColor: "rgba(0,0,0,0.88)",
            textAlign: "center",
            paddingTop: 20,
            width: 400,
            height: 80,
            margin: "auto",
          }}
        >
          GeeksForGeeks
        </p>
      </div>
    );
  }
}
export default App;


componentDidMount

2. Demounting: This is the final phase of the lifecycle of the component that is the phase of unmounting the component from the DOM. The following function is the sole member of this phase.

  • componentWillUnmount() Function: This function is invoked before the component is finally unmounted from the DOM i.e. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle.

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.

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. 

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

App.js




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;


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

npm start

Output:

Demounting

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments