ReactJS componentDidMount() Method
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
}
- The method does not take any arguments.
- It doesn’t return anything.
- It is automatically called by React after the initial render.
When is componentDidMount() Called?
componentDidMount() is called after the initial render of a component. Specifically:
- After the component is rendered to the screen for the first time.
- After the component is added to the DOM.
- Before the browser paints the component’s content.
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:
- Constructor: Initializes state and binds methods.
- render(): Returns the JSX to be rendered.
- componentDidMount(): Called after the first render and after the component is added to the DOM.
- componentWillUnmount(): Cleanup before the component is removed from the DOM.
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

Fetching Data in componentDidMount()
In this example
- componentDidMount() is used to fetch data from an API.
- this.setState() updates the component state once the data is fetched, which triggers a re-render.
- The component initially renders a “Loading…” message, and once the data is fetched, it displays the JSON data.
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
</p>
</div>
);
}
}
export default App;
Output

ReactJS componentDidMount() Method
In this example
- The App component starts with a color state set to “lightgreen”.
- A setInterval is created to call the getRandomColor method every 2 seconds.
- The setState method updates the color state with a new random color generated by getRandomColor().
- The getRandomColor function generates a random color in hexadecimal format.
- The text “GeeksForGeeks” is displayed in the center, and its color changes every 2 seconds.
- The component doesn’t clean up the interval when unmounted, which may lead to a memory leak.
When To Use componentDidMount()?
We should use componentDidMount() in the following scenarios:
- Fetching Data: When you need to retrieve data from an API or external source after the component is rendered.
- Setting Up Subscriptions: When subscribing to data streams or WebSocket connections.
- Initializing Third-Party Libraries: When integrating third-party libraries or plugins that require access to the DOM.
- Event Listeners: Setting up event listeners (e.g., scroll, resize) that should be active once the component is mounted.
- DOM Manipulations: Performing DOM measurements or updates that need to occur after the component is rendered.
Best Practices for using componentDidMount()
- Avoid State Initialization: Use the constructor or getDerivedStateFromProps() for initial state setup; reserve componentDidMount() for side effects like data fetching.
- Use componentWillUnmount() for Cleanup: Always clean up event listeners, subscriptions, or timers in componentWillUnmount() to prevent memory leaks.
- Handle Errors: Use try/catch or .catch() to handle errors in asynchronous operations like data fetching to avoid crashes.
- One-Time Operations: Use componentDidMount() for tasks that should only run once, such as data fetching or initial setup, rather than repeated actions.
- Avoid Heavy Logic: Keep the logic in componentDidMount() minimal to ensure fast rendering and prevent blocking UI updates.
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:
- Safe DOM Manipulation: The DOM is ready, so you can interact with it.
- Data Fetching: Ideal for making API calls after the component is mounted.
- Setting Up Subscriptions: You can initiate subscriptions or timers.
- Third-Party Libraries: Use it to initialize external libraries that need the DOM.
- State Updates: Safely update state based on data or other actions.
When Not to Use componentDidMount()?
There are certain scenarios where using componentDidMount() might be unnecessary:
- No Post-Render Operations Required: If the component’s behavior and appearance are fully determined by its initial render, without needing data fetching, subscriptions, or other after-mount actions, then componentDidMount() is not needed.
- Static or Presentational Components: Components that simply render static content or rely entirely on props for display typically do not require any additional setup after mounting.
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
Similar Reads
ReactJS componentDidUpdate() Method
In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for handling actions after updates have occurred is componentDidUpdate(). This method is called immediately after a componentâs updates are applied to th
5 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() w
2 min read
ReactJS UNSAFE_componentWillMount() Method
The componentWillMount() method invokes right before our React component gets loaded or mounted in the DOM (Document Object Model). It is called during the mounting phase of the React Life-cycle, i.e., before render(). It is used to fetch data from outside the component by executing the React code s
3 min read
What is ComponentWillMount() method in ReactJS ?
ReactJS requires several components to represent a unit of logic for specific functionality. The componentWillMount lifecycle method is an ideal choice when it comes to updating business logic, app configuration updates, and API calls. PrerequisitesReact JSReact JS class componentsComponentWillMount
4 min read
ReactJS isDOMComponent() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isDOMComponent() method. This
2 min read
ReactJS isCompositeComponent() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will see how to use isCompositeComponent() method.
2 min read
ReactJS UNSAFE_componentWillUpdate() Method
The componentWillUpdate() method provides us the control to manipulate our React component just before it receives new props or state values. It is called just before the rendering of our component during the updating phase of the React Life-cycle ,i.e., this method gets triggered after the updation
3 min read
ReactJS Pure Components
ReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS findDOMNode() Method
findDOMNode in React is used to directly access a component's underlying DOM node. It is mainly used in class components for DOM manipulation, animations, or integration with third-party libraries. It's considered unsafe in modern React development. Syntax:ReactDOM.findDOMNode(component)Parameters:
2 min read
ReactJS isElement() Method
React.js library is all about splitting the app into several components. Each Component has its own lifecycle. React provides us some in-built methods that we can override at particular stages in the life-cycle of the component. In this article, we will know how to use isElement() method. The isElem
2 min read