Journey to the React Component Life Cycle


As we all know, our birth cycle has three phase Birth, Growth, Death, the React Component follows the same Birth-Growth-Death life cycle the difference is we can’t control human life cycle but we can control React component’s life cycle :p.

Think a little bit about what a React component does… Based on what we have covered so far in a single sentence: it describes what to render. We already know that it uses the render() method for this purpose. However having only the render() method may not always fulfill our requirements. What if we want to do something before or after the component has rendered or mounted ? What if we want to avoid a re-render?

Looks like we need more control over the stages that a component goes through. The process where all these stages are involved is called the component’s life cycle and every React component goes through it. React provides several methods that notify us when certain stage of this process occurs. These methods are called the component’s life cycle methods and they are invoked in a predictable order.

Now we are going to see the term that we used for React component life cycle:-

  • Mounting: Birth of component.
  • Update: Growth of component.
  • Unmount: Death of component.

Let’s dig deeper into the mechanics of each phase i.e now we are going to discuss different methods used for optimizing the component at each phase.

Mounting

Initialization is the initial phase of journey of Mounting. This is the phase where we initiate the two most important parameter of react component i.e states and props. Generally we did this job done at constructor.

class MyComponent extends Component {
  constructor(props) {
    // calling the props passed by Parent's component.
    super(props);    // Initialization of state
    this.state = {
      counter: 0,
    };  }
}

Note: Initializing the state in constructor is optional , you can also initialize your default state like this :-

class MyComponent extends Component {
    // Initialization of state
    state = {
      counter: 0,
    };
}

Now , initial props and state are set, let’s move on to Mounting stage of the component.

Mounting is the process that occurs when a component is being inserted into the DOM. This phase has two methods that we can hook up with: componentWillMount() and componentDidMount().

  • componentWillMount():- This method is the first one to called in Mounting phase, It’s invoked just before the initial rendering process i.e before react inserts a component into DOM. It’s called just before the render() method and thus there’s no use to of this.setState() inside this method, it will not trigger any re-rendering. In this method we can define global variable or generate auth tokens etc.

  • componentDidMount():- This method is the last one to called in Birth/Mount phase, It’s invoked just after the initial rendering process i.e after react inserts a component into DOM. Similar to componentWillMount(), componentDidMount() is only called one time. Sometimes, it is required that we want to get some data as soon as the component is loaded, hence this is the best place to make API calls and update the state with the API response.

class MyComponent extends Component {
   // Initialization of state
   state = {
     items: [],
   }
   
   componentDidMount() {
     this.getItems();
   }
   
   getItems =() =>{
      // * * * fetch api call * * *
      this.setState({
          items : api_response_data
      })
   }
   
   render() {
     console.log(this.state.items)
     return (
        <div>
           <h3>Hello mounting methods!</h3>
        </div>
     );
  }

UPDATE

This phase starts when the component has taken birth into the world(browser) and grows by receiving updates. The Growth/Update phase is a phase where component spends most of its time. Again relate this phase to human growth phase, as we know in our growing phase we enhance our skills and productivity, similarly during this phase, component provide the overall experience and creativity by receiving updates. Growth phase is triggered in two different ways:-

  • state update.
  • props update.

This is the phase where data of the component(state & props) changes and re-rendering take place.Let’s see the methods that are available in this phase:-

  • shouldComponentUpdate():- As name defined itself, Should the component be updated?. This method determines whether the component should be updated or not. By default it returns true, But if we want to avoid re-rendering at some condition, this method is the right place.

  • componentWillUpdate():- This method is executed, if shouldComponentUpdate() returns true. Similar to componentWillMount(), this method also executed before the rendering, but this method is called every time a re-render is required and we have access to next props and state.

  • componentDidUpdate():- componentDidUpdate() is executed immediately after the component has been updated in the DOM. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

componentDidUpdate(prevProps) {
  if (this.props.obj !== prevProps.obj) {
    this.getItems(this.props.obj);
  }
}

Note:- componentDidUpdate() will not be called if shouldComponentUpdate() returns false.

##Unmount

This is the last phase of React component life cycle, after our Component has spent time in the Update phase, now our component enters the Death phase :( ,this is a phase where our component gets unmounted from the DOM which means it will never be re-rendered.

React provide us only one method for this phase:-

  • componentWillUnmount() It is called immediately before the component is unmounted from the DOM. We can use it to perform any cleanup we might need, such as auth tokens or cleaning up any global elements that were created in componentWillMount()/componentDidMount().

NOTE:- Although there are some methods which are deprecated in the new version of REACT and renamed as UNSAFE_componentWillSomething, methods are:-

componentWillMount()

componentWillUpdate()

The reason for this decision is when asynchronous rendering is implemented in React, misuse of these will be problematic, and the interrupting behavior of error handling could result in memory leaks.

React Lifecycle

I hope you find this article useful and informative.