ReactJS componentDidMount() Method (original) (raw)

Last Updated : 11 Apr, 2025

In React, **componentDidMount() is a lifecycle method in **React that is called once a component has been rendered and placed in the **DOM. This method is invoked only once during the **lifecycle of a component, immediately after the **first render, which is why it is useful for operations like **fetching data, setting up subscriptions, and interacting with the DOM.

**Syntax

componentDidMount(){
// code to be executed }

When is componentDidMount() Called?

componentDidMount() is called after the initial render of a component. Specifically:

Note: It is called once in the component’s lifecycle, meaning it only runs once when the component is first mounted.

How componentDidMount() Works in the Component Lifecycle

In React, a component goes through various phases in its lifecycle, and componentDidMount() is part of the mounting phase. The order of lifecycle methods is as follows:

Implementing componentDidMount() Method

The componentDidMount() method is implemented to perform tasks such as data fetching, setting up subscriptions, or interacting with the DOM after the component has been mounted.

1. Fetching Data in componentDidMount()

In this example, we will use the componentDidMount method for fetching the data.

JavaScript `

import React from 'react';

class DataFetcher extends React.Component { constructor(props) { super(props); this.state = { data: null, loading: true, error: null, }; }

componentDidMount() {
    fetch('https://jsonplaceholder.typicode.com/posts') // Replace with valid API URL
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            this.setState({ data, loading: false });
        })
        .catch(error => {
            console.error('There was a problem with the fetch operation:', error);
            this.setState({ loading: false, error: error.message });
        });
}

render() {
    const { data, loading, error } = this.state;
    return (
        <div>
            {loading && <p>Loading...</p>}
            {error && <p>Error: {error}</p>}
            {data && <pre>{JSON.stringify(data, null, 2)}</pre>}
        </div>
    );
}

}

export default DataFetcher;

`

**Output

Screenshot-2025-02-13-151739

Fetching Data in componentDidMount()

**In this example

2. Name Color Changer Application

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. So, we will use the componentDidMount() method here.

JavaScript `

import React from "react"; class App extends React.Component { constructor(props) { super(props); this.state = { color: "lightgreen" }; } componentDidMount() { this.interval = setInterval(() => { this.setState({ color: this.getRandomColor() }); }, 2000); } getRandomColor = () => { const letters = "0123456789ABCDEF"; let color = "#"; for (let i = 0; i < 6; i++) { color += letters[Math.floor(Math.random() * 16)]; } return color; }; render() { return ( <div style={{ display: "flex", justifyContent: "center", alignItems: "center", height: "100vh", backgroundColor: "#282c34", }} > <p style={{ color: this.state.color, backgroundColor: "#333", textAlign: "center", padding: "20px", borderRadius: "12px", boxShadow: "0px 4px 10px rgba(0, 0, 0, 0.5)", fontFamily: "Arial, sans-serif", fontSize: "1.5rem", width: "300px", margin: "auto", }} > GeeksForGeeks

); } } export default App;

`

**Output

componentDidMount

ReactJS componentDidMount() Method

**In this example

When To Use componentDidMount()?

We should use componentDidMount() in the following scenarios:

Best Practices for using componentDidMount()

Difference Between componentDidMount() Method and componentWillMount()

Aspect componentWillMount() componentDidMount()
Timing Called before the component is mounted to the DOM. Called after the component is mounted to the DOM.
Usage Typically used for setting initial state or performing any pre-render tasks. Note: It is now deprecated in newer versions of React. Used for tasks like data fetching, setting up subscriptions, and initializing third-party libraries once the component is rendered.
Component Availability The component is not yet in the DOM, so DOM manipulations or side effects should not be done. The component is fully rendered and mounted to the DOM, so it is safe to manipulate the DOM and perform side effects.
Side Effects Avoid side effects, as they might cause issues with the DOM rendering. Ideal for side effects such as API calls, initializing external libraries, or setting up timers.
State Updates Updating the state here might cause issues, especially since the component isn't rendered yet. You can safely update the state here, as the component is already in the DOM and React will trigger a re-render if needed.
Deprecation componentWillMount() has been deprecated in React 16.3+ in favor of getDerivedStateFromProps and constructor. componentDidMount() is still actively used and recommended for handling tasks after the component mounts.

Benefits of componentDidMount() Method

The componentDidMount() method offers several benefits:

When Not to Use componentDidMount()?

There are certain scenarios where using componentDidMount() might be unnecessary:

Conclusion

The **componentDidMount() method is an essential tool in React for performing setup tasks, such as **fetching data, initializing **third-party libraries, and setting up subscriptions, after a component has been added to the **DOM