Skip to content
Related Articles

Related Articles

ReactJS componentDidMount() Method
  • Last Updated : 20 Dec, 2020

The componentDidMount() method allows us to execute the React code when the component is already placed in the DOM (Document Object Model). This method is called during the Mounting phase of the React Life-cycle i.e after the component is rendered.

All the AJAX requests and the DOM or state updation should be coded in the componentDidMount() method block. We can also set up all the major subscriptions here but to avoid any performance issues, always remember to unsubscribe them in the componentWillUnmount() method.

Syntax:

componentDidMount()

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.

Project Structure

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.

Javascript




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;

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

npm start

Output: 

My Personal Notes arrow_drop_up
Recommended Articles
Page :