Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
ReactJS componentDidMount() Method
Next article icon

ReactJS componentDidMount() Method

Last Updated : 11 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

Screenshot-2025-02-13-151739
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

componentDidMount
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


Next Article
ReactJS componentDidMount() Method

R

rbbansal
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-LifeCycle-Methods

Similar Reads

    ReactJS componentWillUnmount() Method
    In React, lifecycle methods allow you to manage the behaviour of components at different stages of their existence. One important lifecycle method for cleaning up resources and side effects is componentWillUnmount(). This method is called just before a component is removed from the DOM, making it an
    5 min read
    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 componentsComponentWillMoun
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences