Sunday, February 21, 2021

React Components Lifecycle

We have learned so far that the React web applications are actually a collection of independent components that run according to the interactions made with them. Each component in React has a life-cycle that you can monitor and change during its three main phases. There are three phases: Mounting, Updating, and Unmounting. You can use life-cycle methods to run a part of code at particular times in the process or application. You can refer to the below diagram to get a visual idea of the life-cycle methods and their interactions in each phase.

Mounting

Mounting is the phase when the component is mounted on the DOM and then rendered on the webpage. We call these methods in the following order when an element is being created and inserted into the DOM:

  • componentWillMount()
  • render()
  • componentDidMount()

componentWillMount(): This function is called right before we mount the component on the DOM. So after this method executes, the component gets mounted on the DOM. It executes this method before the first render of the React application. So all the tasks that have to be done before the component mounts are defined in this method.

render(): This function mounts the component on the browser. 

componentDidMount(): We invoke this function right after the component is mounted on the DOM i.e., this function gets called once after the render() function is executed for the first time. Generally, in React applications, we do the API calls within this method.


Updating

We call the methods in this phase whenever State or Props in a component get updated. This allows the React application to “react” to user inputs, such as clicks and pressing keys on the keyboard, and ultimately create a responsive web user interface. These methods are called in the following order to carry on the update of the component:

  • componentWillReceiveProps()
  • setState()
  • shouldComponentUpdate()
  • componentWillUpdate()
  • render()
  • componentDidUpdate()

componentWillRecieveProps(): We call This function before a component gets its props reassigned. 

setState(): This function can be called explicitly at any moment. This function is used to update the state of a component.

shouldComponentUpdate(): This function is called before rendering a component and tells React whether it should update the component on receiving new props or state. It takes the new Props and new State as the arguments and returns whether or not to re-render the component by returning either True or False.

componentWillUpdate(): This function is called once before the render() function is executed after the update of State or Props.

render(): The component gets rendered when this function is called.

componentDidUpdate(): This function is called once after the render() function is executed after the update of State or Props.


Unmounting

This is the last phase of the life-cycle of the component where the component is unmounted from the DOM. This phase has only one method:

componentWillUnmount(): This function is called once before we remove the component from the page and this marks the end of the life-cycle.

Now that we are familiar with all the life-cycle methods of React components, let us now look at an example to see how each function is implemented in the application code: 

DisplayCycle.js

import React from "react";
import DisplayChild from "./DisplayChild";

class DisplayCycle extends React.Component {
  constructor(props) {
    super(props);
    this.state = { name: "Pankaj" };
    console.log("Constructor");
  }
  componentWillMount() {
    console.log("componentWillMount Parent");
  }
  componentDidMount() {
    console.log("componentDidMount Parent");
  }
  shouldComponentUpdate() {
    console.log("shouldComponentUpdate parent");
    return true;
  }
  componentWillUpdate() {
    console.log("componentWillUpdate() called");
  }

  componentDidUpdate() {
    console.log("componentDidUpdate() called");
  }
  componentWillUnmount() {
    console.log("componentWillUnmount() called");
  }
  switchState = () => {
    this.setState({ name: "pankaj Kapoor" });
  };
  render() {
    console.log("render Parent");
    return (
      <div>
        <input type="text" value={this.state.name} />
        <DisplayChild firstname={this.state.name} />
        <button onClick={this.switchState}>Click Me</button>
      </div>
    );
  }
}

export default DisplayCycle;

Output: