componentDidMount() in ReactJS

componentDidMount() method of component is invoked immediately after component is added to DOM ( mounted to DOM ).

componentDidMount() method is only called once in mounting phase of component.

Why componentDidMount() should be used?

componentDidMount() method is the place where you can do all the side effect work which should be done after the component is added to DOM.

Following is the list for which componentDidMount() method can be used.

  • You can make API request to server in componentDidMount()
  • You can make any subscriptions in componentDidMount() and unsubscibe it in componentWillUnmount() method.
  • You can use any third party library like Highcharts or D3 which is used when DOM is ready in componentDidMount().
    If some calculation needs to be done on DOM elements e.g. show tooltip or show modal, it should be done in componentDidMount() method.

Points to remember while using componentDidMount()

You can call setState() inside componentDidMount() but that would call render() method.

So if possible, initialize state object because it would create some performance issue.


In this section, we learned about componentDidMount() method and for what it can be used.
In the next section, you will learn about shouldcomponentupdate() method of ReactJS component.