Open In App

ReactJS componentDidMount() Method

Last Updated : 09 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The componentDidMount method in react is used to execute some code immediately after mounting. This is a lifecycle method in React class component that is called only once when the component is mounted in the DOM.

This method helps to execute when the component is rendered on the page.

Syntax:

componentDidMount(){
// code to execute
}

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. Understanding this method is crucial for handling side effects and initializing data. To gain deeper insights into React’s lifecycle methods, consider enrolling in the ReactJS Course, which covers these concepts in detail.

Steps to Create 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.

JavaScript
// Filename - 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;

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

npm start

Output: 

Summary

componentDidMount is a React lifecycle method in class components, called once after a component mounts to the DOM. It’s used for tasks like fetching data, setting up subscriptions, or manipulating the DOM, ensuring these actions occur post-render.



Next Article

Similar Reads

Article Tags :
three90RightbarBannerImg
  翻译: