Skip to content
Related Articles

Related Articles

What does it mean for a component to be mounted in ReactJS ?

View Discussion
Improve Article
Save Article
  • Last Updated : 27 Mar, 2022

In React, every instance of a component goes through a lifecycle that consists of creation (mounting), updating, and deletion (unmounting). 

Mounting is the initial phase in which the instance of the component is created and inserted into the DOM. When the component gets successfully inserted into the DOM, the component is said to be mounted. In the updating phase, the component gets updated while being present in the DOM. In the unmounting phase, the component is removed from the DOM.

React provides us various methods called the lifecycle methods which get triggered during different phases of the lifecycle of that component. We will use some of these lifecycle methods to see what happens in the mounting phase.

Creating React Application:

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

npx create-react-app mountdemo

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

cd mountdemo

Project Structure: It will look like the following.

Project Structure

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. The below demo app displays a number that gets incremented on clicking the button. 

Javascript




import React from 'react';
  
class App extends React.Component{
  
  constructor(props){
    super(props);
    this.state = { num: 0 };
    this.clickHandler = this.clickHandler.bind(this);
  }
  
  // Button onClick callback function
  clickHandler (event){
    this.setState(state => ({num: state.num + 1}))
  }
  
  // Component lifecycle methods
  // Triggered when component is mounted
  componentDidMount(){
    console.log("Mounted");
  }
    
  // Triggered when component is updated
  componentDidUpdate(){
    console.log("Updated");
  }
  
  render() {
    console.log("Rendered");
    return (
      <div>
        <h1>Demo App</h1>
        <p>Number: {this.state.num}</p>
        <button onClick={this.clickHandler}>increment</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:

Visualizing console output 

Note: From the output, note that the component is mounted only after the initial render. After updating the state, the component is only re-rendered.

Conclusion: We saw that the component is mounted when it has been created and inserted into the DOM. Also, updating the component will re-render the component and not mount it again.

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


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!