Open In App

ReactJS componentDidMount() Method

Last Updated : 20 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

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: 



Similar Reads

What is the significance of the componentDidMount lifecycle method?
Every React Component has a lifecycle of its own, the lifecycle of a component can be defined as the series of methods that are invoked in different stages of the component’s existence. In this article, we will dive into the componentDidMount and see the significance of it. Prerequisites:NPM &amp; NodeReact JSReact JS Class ComponentsWhat is compon
3 min read
How useEffect replaces componentDidMount and componentDidUpdate methods?
In React, the useEffect hook can be used to replicate the behavior of both componentDidMount and componentDidUpdate lifecycle methods. Here's how you can achieve that: componentDidMount Equivalent:When you want to perform some actions immediately after the component mounts, you can use useEffect with an empty dependency array ([]). This ensures tha
2 min read
How to simulate componentDidMount with useEffect?
componentDidMount is a lifecycle method that runs after a component has been mounted or rendered to the DOM. It's often used for tasks like fetching data from an API or setting up event listeners. Simulating componentDidMount with useEffect:In functional components, you can achieve similar behavior using the useEffect hook.To simulate componentDidM
2 min read
ReactJS shouldComponentUpdate() Method
The shouldComponentUpdate method allows us to exit the complex react update life cycle to avoid calling it again and again on every re-render. It only updates the component if the props passed to it changes. The shouldComponentUpdate method is majorly used for optimizing the performance and to increase the responsiveness of the website but do not r
3 min read
ReactJS getSnapshotBeforeUpdate() Method
The getSnapshotBeforeUpdate() method is invoked just before the DOM is being rendered. It is used to store the previous values of the state after the DOM is updated. Any value returned by getSnapshotBeforeUpdate() method will be used as a parameter for componentDidUpdate() method. This function is always used along with the componentDidUpdate() met
2 min read
ReactJS bind() Method
The bind() is an inbuilt method in React that is used to pass the data as an argument to the function of a class based component. Syntax: this.function.bind(this,[arg1...]);Parameter: It accepts two parameters, the first parameter is the this keyword used for binding and the second parameter is the sequence of arguments that are passed as a paramet
2 min read
ReactJS componentWillUnmount() Method
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 cle
2 min read
ReactJS componentDidUpdate() Method
The componentDidUpdate() method allows us to execute the React code when the component is updated. All the network requests that are to be made when the props passed to the component changes are coded here. The componentDidUpdate()is called after componentDidMount() and can be useful to perform some action when the state of the component changes. S
2 min read
ReactJS getDerivedStateFromError() Method
The getDerivedStateFromError() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the render phase, so side-effects are not permitted in this method. For side-effects, use component
2 min read
ReactJS componentDidCatch() Method
The componentDidCatch() method is invoked if some error occurs during the rendering phase of any lifecycle methods or any children components. This method is used to implement the Error Boundaries for the React application. It is called during the commit phase, so unlike getDerivedStateFromError() which was called during the render phase, side-effe
2 min read
Article Tags :