What is mounted component in React?

Experience Level: Junior
Tags: React

Answer

In React, a mounted component is a component that has been rendered and inserted into the DOM. When a component is mounted, it means that its lifecycle methods have been called and it is now ready to be interacted with by the user. This is an important concept in React because it allows for dynamic updates to the UI without having to reload the entire page.

When a component is mounted, it goes through a series of lifecycle methods. These methods include componentWillMount, componentDidMount, componentWillReceiveProps, shouldComponentUpdate, componentWillUpdate, componentDidUpdate, and componentWillUnmount. Each of these methods is called at a specific point in the component's lifecycle and allows for developers to control how the component behaves at each stage.

Here is an example of a mounted component in React:


class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  componentDidMount() {
    console.log('Component mounted');
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })>Increment</button>
      </div>
    );
  }
}

ReactDOM.render(<MyComponent />, document.getElementById('root'));

In this example, the MyComponent class is a mounted component because it has been rendered and inserted into the DOM. When the component is mounted, the componentDidMount method is called, which logs 'Component mounted' to the console. The component also has a button that, when clicked, increments the count state variable and updates the UI without reloading the page.

React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself