Understanding componentDidMount in React js 2025

Understanding React's componentDidMount

The `componentDidMount` lifecycle method in React is one of the most commonly used methods. It is called after a component has been rendered to the screen. This method is a great place to initiate AJAX requests, add event listeners, or perform any other operations that require the component to be in the DOM. Let's dive into a deeper explanation with a practical example.

What is componentDidMount?

`componentDidMount` is a built-in React lifecycle method for class components. It is called automatically by React when the component is inserted into the DOM. This method is used for tasks like fetching data, interacting with external APIs, or setting up subscriptions that require the component to be in the DOM before proceeding.

When is it called?

It is called immediately after the component is mounted (i.e., when the component has been inserted into the DOM). Itโ€™s important to note that the rendering has already been completed at this point. Therefore, any side-effects you want to trigger after the render can be placed inside `componentDidMount`.

Practical Example:

Hereโ€™s a simple example where we use `componentDidMount` to fetch data from an API:

                
{`import React from 'react';

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

    // This will run once the component has mounted
    componentDidMount() {
        // Fetch data from an API
        fetch('https://jsonplaceholder.typicode.com/posts')
            .then((response) => response.json())
            .then((data) => {
                // Update the state with the fetched data
                this.setState({ data: data, loading: false });
            })
            .catch((error) => {
                console.error('Error fetching data:', error);
                this.setState({ loading: false });
            });
    }

    render() {
        const { data, loading } = this.state;
        if (loading) {
            return 

Loading...

; } return (

Fetched Data

    {data.map((item) => (
  • {item.title}
  • ))}
); } } export default FetchDataComponent;`}

Key Points to Remember:

  • The method is called once after the component has been rendered into the DOM.
  • Itโ€™s ideal for AJAX calls or data fetching after the initial render.
  • If you need to perform clean-up tasks (e.g., canceling subscriptions or timers), you can use `componentWillUnmount`.
  • It runs only once per component lifecycle, after the first render.

Conclusion:

In summary, `componentDidMount` is crucial for performing side-effects like data fetching, event listeners, or setting up external libraries. It's one of the most useful lifecycle methods in class components, but if you're working with functional components, consider using the `useEffect` hook, which offers similar functionality.