React Component Mounting Phase

Aug 04, 2019

The getInitialState method

The getInitialState() method is invoked first. It is invoked before React inserts a component into the DOM. If you want your component to have a state, then use this method to return the initial component's state.

getInitialState: function () {
  console.log('getInitialState called');

  return {
     state ...

The componentWillMount method

The componentWillMount() method is invoked second. It is invoked immediately before React inserts a component into the DOM.

componentWillMount: function () {
  console.log('componentWillMount called') 
  //You can fetch any data here which is required in your component

Now if you can fetch data in Component will mount meathodthen ofcourse you can set state in this meathod also  and

As you know, calling the this.setState() method should trigger the component's render() method, so it seems like render() will be called twice during the component's mounting phase. However, in this case, React knows that nothing has been rendered yet, so it will call the render() method only once.

The componentDidMount method

The componentDidMount() method is invoked third. It is invoked immediately after React inserts a component into the DOM. The updated DOM is now available for access, which means that this method is the best place for initializing other JavaScript libraries that need access to that DOM.

If you are using another JavaScript library such as jQuery, along with React, then use the componentDidMount() method as an opportunity to integrate the two. If you want to send an AJAX request or set timers using the setTimeout() or setInterval() functions, then you can do that in this method as well. In general, componentDidMount() should be your preferred component lifecycle method for integrating the React library with non-React libraries and APIs.

So far, in this article, we've learned about the fundamental mounting methods that the React component provides us with. .  On its very first render, React will execute the following sequence of methods:

  1. getInitialState()
  2. componentWillMount()
  3. render()
  4. componentDidMount()

This is called the React component's mounting phase. It's executed only once, unless we unmount a component and mount it again.

Neeraj Dana

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in Angular, React, React-Native, Vue js, Machine Learning