HomeBlogWeb DevelopmentReact JS componentDidMount() Method [With Examples]

React JS componentDidMount() Method [With Examples]

Published
02nd Jun, 2024
Views
view count loader
Read it in
10 Mins
In this article
    React JS componentDidMount() Method [With Examples]

    During the creation of my first React component, I started injecting fetch calls before the class component and even within the render () method. I grunted as a result of the strange side effects of my application. As part of my research, I found a lifecycle for React called componentDidMount().

    I found that calling all the APIs into componentDidMount() resolved my problem, but it raised new questions.

    1. What is componentDidMount() in React?
    2. How many times does componentDidMount() run?
    3. Is it safe to use async/await in componentDidMount?

    The advanced React course is accessible for individuals interested in becoming skilled React developers. In this article, we will go through what is componentDidMount(), benefits of using ‘componentDidMount()’ in ReactJS, best practices, and more.

    What is React componentDidMount()?

    React componentDidMount
    DevtipAs the name suggests, the componentDidMount method is invoked after all the elements of the page have been rendered correctly, aka after the first render () cycle. This is the final step of the mounting process. This technique is known as "post mounting". The method is called when all the child elements and components have been mounted in the Document Object Model (DOM).

    During the mounting phase of React's lifecycle, you can set up network requests or subscriptions in the componentDidMount method, but to avoid any performance issues, these requests must be unsubscribed in the componentWillUnmount method.

    Example of React componentDidMount()

    The example below shows a classical approach to access componentDidMount().

    import React, { Component } from 'react';
    class App extends Component {
        componentDidMount() {
          // Runs after the first render() lifecycle
          console.log("Did mount called");
        }
        render() {
          console.log('Render lifecycle')
          return <h1>Hello World!</h1>;
        }
    }
    export default App;  

    See the output below:

    1. Render Lifecycle is called first means console of render function is printed.
    2. Did mount called (first call after the component is mounted on DOM or after completion of render)

    Classical approach to access componentDidMount()

    Benefits of Using ‘componentDidMount()’ in ReactJS

    The ‘componentDidMount()’ method in ReactJS is a powerful tool that offers several key benefits, making it an essential aspect of the component lifecycle.

    The tasks within componentDidMount() execute only after the component is fully rendered and inserted into the DOM, guaranteeing its availability for interactions. Sometimes, we want to get information from an external API or perform other asynchronous operations. The componentDidMount() method is perfect for doing this. We can make AJAX requests using JavaScript’s bring or axios libraries to retrieve data from the server. Once we get the information back, we can show it on the page or make the page refresh with the new stuff. Using componentDidMount() makes sure these tasks happen after the page is all set up and ready to go.

    We also set up event listeners and subscriptions to external data sources within componentDidMount() to establish dynamic interactions and data flows that respond to user actions and external changes. For example, if I want my component to listen for live updates from a WebSocket or something similar, I can set that up here. Doing it this way makes sure the listening starts only once, and then I can respond when updates come in.

    This timing is crucial for interactions like fetching data from APIs, initializing third-party libraries, or setting up subscriptions. By using ‘componentDidMount()’, we ensure that these operations occur precisely when the component is ready, preventing potential conflicts or undefined behavior.

    How to Use setState in componentDidMount? 

    The componentDidMount() method is the perfect place for us to call the setState() method to change the state of our application. Then we can render the updated JSX data.

    If you look at the code below, I've made an API call with the setTimeOut function and fetched data. So after the component has been rendered correctly, the componentDidMount() method is called, and that internally calls the fetchData() method where the state of the data is changed from "Sonia Pahuja" to "Hello World!".

    import React, { Component } from 'react';
    class DemoLifecycle extends Component {
      constructor(props){
        super(props);
        this.state = {
          data: 'Sonia Pahuja'
        }
      }
      fetchData(){
        setTimeout(() => {
          console.log('Our data is fetched');
          this.setState({
            data: 'Hello World!'
          })
        }, 1000)
      }
      componentDidMount(){
        this.fetchData();
      }
      render() {
        return(
          <div>
          {this.state.data}
        </div>
        )
      }
    }
    export default DemoLifecycle;

    When Dom is Initially Rendered, What Happens? 

    1. The initial data is displayed on the DOM, i.e., the name "Sonia Pahuja".
    2. The componentDidMount() is called, which internally calls another function, i.e., fetchData().
    3. The console will display "Our data is fetched."
    4. This is the new state of our application. "Sonia Pahuja" is now "Hello World!".
    5. This will again trigger a re-render, and finally, "Hello World" will be visible on the DOM.

    This is how setstate works in componentDidMount.

    How Many Times Does React componentDidMount() Run? 

    React components call componentDidMount only once by default. You can only run the component again if you delete the component or change the key prop value.

    Let’s look at an example where a React component only triggers componentDidMount() once.

    I have a parent component with a button to increment the counter. The counter is initially set to 0. The counter is incremented after clicking the button. The Child Component is displaying the final count.

    A. DemoLifecycle (Parent Component)

    class DemoLifecycle extends Component {
      constructor(props){
        super(props);
        this.state = {
          counter: 0
        }
      }
      componentDidMount() {
        console.log('componentDidMount() lifecycle of parent called');
      }
     incrementHandler = () => {
        this.setState(state => ({counter: state.counter + 1})
        )
      }
      render() {
        console.log('render() lifecycle - Parent');
        return(
          <div>
           <button onClick={this.incrementHandler}>Click to Increment</button>
           <ChildComp number={this.state.counter} />
        </div>
        )
      }
    }
    export default DemoLifecycle;

    B. Child Component

    import React, { Component } from 'react';
    class ChildComp extends React.Component {
        componentDidMount() {
          console.log('componentDidMount() lifecycle of child called')
        }
        render() {
            console.log('render() lifecycle - Child');
          return <h1>{this.props.number} times</h1>;
        }
    }

    Output

    How Many Times Does componentDidMount() Run?

    The above example prints the render and shows how the componentDidMount lifecycle triggers using console.log().

    At first glance, this is the order in which the methods are called.

    1. The parent render method is called.
    2. The child render method is called.
    3. ComponentDidMount of a child is called
    4. ComponentDidMount of Parent is called.

    I have now changed my counter from 0 to 6 after clicking the increment button six times.

    Observe that only render methods are called in the console. There is no call to ComponentDidMount. It is only called once after the initial render.

    How Many Times Does componentDidMount() Run?

    Let's take a look at how componentDidMount() could be called many times. I'm going to use the same code as the previous example, but I'm going to add a new property to the <ChildComp/> component called a key. You should now see the following output when you press the increment button.

    How Many Times Does componentDidMount() Run?

    With the help of a key prop, React will keep a watch on that component and cause a componentWillUnmount if the value changes. When the ChildComp remounts, ComponentDidMount() will be called again.

    What is the Key Prop?

    The key property in React is a unique property that distinguishes HTML elements or a React component in React. These values have to be very unique to the element or component. By using keys, React can recognize which items have been changed, added, or removed. A stable identity should be assigned to each element within the array.

    Are you more interested in learning deeper concepts of web development? You can refer KnowledgeHut’s Web Development Course.

    How to Use React componentDidMount() in Functional Components?

    Prior to react hooks, we used class-based components to manage a state or a lifecycle. However, functional components now have the potential to have states and lifecycle methods thanks to this new functionality.

    Normally, inside a class component, componentDidMount() is utilized in the following way:

    componentDidMount() {
        fetch(url)
        .then(response => response.json())
        .then(data => this.setState())
    }

    Functional components didn't have access to lifecycle functions before hooks, therefore if you wish to perform an HTTP request, you'd do it like this without using componentDidMount.

    const ScoreBoard= props => {
        const [score, setScore] = useState([])
          fetch(url)
          .then(resp => resp.json())
          .then(data => this.setState()
           return() {
             // some code  
       }
    }

    The following problems will arise as a result:

    • Every time the <ScoreBoard/> is re-rendered, an HTTP request is sent, which is unlikely to be useful.
    • Whenever you fetch something, the state is reset.
    • Lastly, since setScore() redraws the scoreboard each time, the loop runs infinitely.

    Here's where the useEffect hook comes into play. Check out the following code snippet.

    const ScoreBoard = props => {
        const [score, setScore] = useState([]);
        useEffect(() => {
            fetch(url)
                .then(resp => resp.json())
                .then(data => setScore(data.list))
            })
        return()
    }

    We provide a second argument in order to prevent unnecessary calls to the function, as well as the infinite loop issue.

    useEffect(() => {
       fetch(url)
       .then(response => response.json())
       .then(data => setScore(data.list))
    },[])

    UseEffect will behave like componentDidMount if you pass blank array i.e. [] as the second argument. It knows that since your effect is not dependent on any props or state values, it will never re-run.  

    By default, useEffect() runs on every component update, but by passing an array of dependents, in this example, none, it never runs again.

    Let's add some dependencies and see what happens.

    useEffect(() => {
       fetch(url)
       .then(response => response.json())
       .then(data => setScore(data.list))
    },[score])

    Instead of passing a blank array, i.e., no dependencies, we now pass the score. When the score changes, the function will be called again, which is effectively componentDidUpdate().

    Best Practices of Using React componentDidMount()

    Here are some best practices to ensure we use componentDidMount optimally in our application: 

    1. When we are working with real-time updates or subscriptions, we know that we should initialize these connections in componentDidMount(). But we should also ensure these connections are properly terminated in componentWillUnmount() to prevent memory leaks or conflicts with other components. 
    2. While componentDidMount() is a suitable place for side effects, we should try to limit complex operations directly within this method. Instead, we should delegate these tasks to dedicated functions or custom hooks for better code readability and maintainability. 
    3. We should be cautious with operations that might cause re-renders. If setting state inside componentDidMount() triggers re-renders, we should consider alternative lifecycle methods or techniques like using ‘componentDidUpdate()’ or ‘useEffect()’ hooks in functional components. 
    4. We should consider whether data fetching should occur every time the component mounts or only under certain conditions. We should implement logic to prevent unnecessary API calls, improving performance. We can utilize state or props changes as triggers for fetching data inside componentDidMount(). 

    Can We Use Async/Await in React componentDidMount?

    In React, componentDidMount is a good place to use async/await. The following are the steps for using async/await in React:

    • Configure babel
    • Insert the async keyword in front of componentDidMount.
    • Use await in the function's body.
    • Ensure that any potential errors are caught.
    async componentDidMount() {
      const response = await fetch('https://examples.com')
      const jsonData = await response.json()
      this.setState({ data: jsonData })
    }

    Things to Remember componentDidMount() Method

    • componentDidMount() only runs once after the first render.
    • componentDidMount() may be called multiple times if the key prop value for the component changes.
    • componentDidMount method is used for handling all network requests and setting up subscriptions during the mounting phase.
    • It is safe to use async/await with the componentDidMount() method.

    Interested in learning React JS? Check out the KnowledgeHut’s React Full Course.

    Looking to master Python? Discover the best course to learn Python and unlock endless possibilities. Start your coding journey today!

    Conclusion

    We learned how to use the componentDidMount() method. The componentDidMount method is like a launchpad for setting up things or making actions happen as soon as the component is ready to roll. This method gives us the power to safely mess around with how things look or behave on the page. This method is used to interact with the page's structure (DOM), fetch data from servers, or initialize external tools or resources, ensuring everything works smoothly once the component is set up. We talked through how it works and several examples that will help you understand how to use it in React applications. I hope that this article has helped you understand componentDidMount().

    Question / Comments? Feel free to leave them in the comments below.  

    Thanks for reading!

    Frequently Asked Questions (FAQs)

    1What is the use of componentDidMount() in React?

    componentDidMount is the final step of the mounting process. Using the componentDidMount() method, we can execute the React code when the component has already been placed in the DOM (Document Object Model). It is used for handling for handling all network requests and setting up subscriptions.

    2How many times componentDidMount is called?

    React components call componentDidMount only once by default. You can run the component multiple times if you delete the component or change the props or state.

    3Is ComponentDidMount the same as UseEffect?

    Yes, useEffect hook is used in functional component which behave like componentDidMount if you pass blank array i.e. [] as the second argument.

    4Is ComponentDidMount deprecated?

    The method componentDidMount isn't deprecated and is perfectly safe to use, so it does not need to be accompanied by UNSAFE. ComponentWillMount() will be deprecated in the future releases.

    5Why API are called in componentDidMount?

    It is not a syntax error to invoke APIs in constructor() or componentWillMount(), but it increases code complexity and hampers performance. As a result, to avoid unnecessary re-rendering and code complexity, the API should be called after render(), i.e. in componentDidMount().

    6What is replacing componentWillMount?

    In the future releases of React, componentWillMount() will be deprecated. ComponentDidMount() or useEffect hook are recommended as its alternative. However, you can still use ComponentWillMount() by calling it UNSAFE_ComponentWillMount().

    Profile

    Sachin Bhatnagar

    Blog Author

    Sachin Bhatnagar is an experienced education professional with 20+ years of expertise in Media & Entertainment and Web Technologies. Currently, as the Program Director - Full-Stack at KnowledgeHut, he excels in curriculum development, hands-on training, and strategic deployment of industry-centric educational programs. His online training programs on have attracted over 25,000 learners since 2014. He actively contributes to the development of full-stack training products, leveraging KnowledgeHut's advanced learning platform. Collaborating with organizational leaders, he ensures the success of these programs and has created several technology programs prominently featured in KnowledgeHut's course offerings.

    Share This Article
    Ready to Master the Skills that Drive Your Career?

    Avail your free 1:1 mentorship session.

    Select
    Your Message (Optional)

    Upcoming Web Development Batches & Dates

    NameDateFeeKnow more
    Course advisor icon
    Course Advisor
    Whatsapp/Chat icon