Every component in React goes through a lifecycle of events. You can think is of going through a cycle of birth, growth, and death the same as the picture below.

Human and React Lifecycle comparison

Human and React Lifecycle

The phases are:

  • Initialization — Starting the journey of your component
  • Mounting — Birth of your component
  • Update — Growth of your component
  • Unmount — Death of your component

Image for post

1. Initialization

This is the phase in which the component is going to start its journey. The developer has to define the props and initial state of the component. This is usually done inside the constructor method (see below to understand the initialization phase better).

class Increment extends React.Component {constructor(props){super(props);// Setting the initial statethis.state = { count : 0};}}

2. Mounting

Mounting is the phase of the component lifecycle when the initialization of the component is completed and the React component mounts on the DOM (i.e., is created and inserted into the DOM) and rendered for the first time on the webpage. It has 2 predefined functions:-

  • componentWillMount(): As the name clearly suggests, This method is invoked just before a component mounts on the DOM, i.e. this function gets invoked once before the render() function is executed for the first time. After this method, the component gets mounted.
  • componentDidMount(): Similarly to the previous one this method is called after the component gets mounted on the DOM and only once in a lifecycle. Before the execution of this method, the render method is called (i.e., we can access the DOM). We can make API calls and update the state with the API response.
class ReactCycle extends React.Component {
  componentWillMount() {
      console.log('Component will mount!')
   }
  componentDidMount() {
      console.log('Component did mount!')
      this.getData();
   }
  getData=()=>{
   /*** method to make api call***
  }
  render() {
      return (
         <div>
            <h3>Hello mounting methods!</h3>
         </div>
      );
   }
}

#react #web-development #javascript #programming #developer

The Component Life Cycles of ReactJS
4.45 GEEK