React Components Lifecycle Methods - WTH are they?
Tags: react, javascript, beginners, codenewbie
Published: 2020-11-25 08:57:12

## Introduction 👋
Every component in React has it's own **lifecycle**. But before going in depth to that, 🤔 we should know what exactly is Lifecycle of a React Component, and why do I need to know it? 

![Question](https://dev-to-uploads.s3.amazonaws.com/i/6jdyavgv284dl0ehrzm6.gif) 

A _Lifecycle_ is nothing but a sequence of methods that are executed at different stages of the component's existence. Each react component has several _"Lifecycle Methods"_. We need to know these methods so that we can override them when we want to run some code at a particular time in the process.

### 🌱 Phases of a React Component
There are 4 Phases of a Component:
1. **_Mounting_** : During this phase, the Component is initialized and the inserted into the DOM.
2. **_Updating_** : If there is already a Component rendered on the DOM, then any updates are done to the Component as part of the Updating phase.
3. **_Error Handling_**: This Phase is responsible for taking care of the error found during rendering in lifecycle method or in the constructor or any other child components.
4. **_Unmounting_**: During this phase, removing of component from the DOM as well as cleanup activities are done.


![React Lifecycle Methods](https://dev-to-uploads.s3.amazonaws.com/i/di74f0jivvxwhelmqhof.png)

## 🧬 Lifecycle Methods
Now that we know the different phases of a React Component, lets now try to understand the different Lifecycle Methods that are invoked during each phase.
### 1. 🐇 _Mounting Phase:_
At this phase the Component is created with _props_ and _state_ which are initialized within a constructor. Once ready with props and state, the component is ready to _mount_ on to the DOM and is rendered for the first time on the web page.

The methods in the Mounting Phase are:
#### 1. _constructor():_

  * This is the first method that is called for any component.
  * The main purpose of constructor is to initialize the props and state. Along with that, it also _binds_ the events with _'this'_ i.e. the Instance.
  * The constructor includes a call to the _super()_ along with the initialization of _this.state_.
  * One thing to keep in mind is that, the initialization of the state can be done without the constructor() method too and it'll work the same.

  ```javascript
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }
  }
  ```

#### 2. _getDerivedStateFromProps()_

  * Just before rendering the component on the DOM, getDerivedStateFromProps method is called.
  * This method is called when the state of the component depends on the props. 
  * Basically, this method allows the component to change it's state when there is any change in the props.
  * This is used very rarely, but its important to understand it's the order of execution as this method is called in Mounting Phase as well as in Updating phase.

  Continuing the above code snippet:
  ```javascript
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }

        static getDerivedStateFromProps(props, state) {
                console.log('Inside React Component
                        getDerivedStateFromProps');
          }
  }
  ```

#### 3. _render()_

  * We write the _JSX_ code inside this method which will be rendered on the DOM.
  * This is the only method that is required when we are creating a Component in React.
  * This method does not modify the state, it simply returns the same result each time it is invoked.
  * render() method observes the props and state values and it returns either of the following:
   * React Element
   * Array
   * Fragment
   * Strings, numbers, booleans or null

```javascript
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }

        static getDerivedStateFromProps(props, state) {
                console.log('Inside React Component
                        getDerivedStateFromProps');
          }

        render() {
                console.log('Inside render method');
                return <div> This is the App Component </div>
        }          
  }
  ```

#### 4. _componentDidMount()_

* As soon as the component is _mounted / inserted_ into the DOM tree, this method gets called.
* Unlike _render()_, this method is called only once and that too on the Mounting phase. This makes this method the most suitable place for loading data from remote endpoints or making a network request.
* We can even call the _setState()_ method from within this method to modify the state and ultimately recall the _render()_ to update the contents of the DOM.
* This method ensures that the user won't see any intermediate states even though _render()_ method is called twice.

```javascript
  import React from 'react';

  class AppComp extends React.Component {
        constructor(props) {
                super(props);
                this.state = {
                        title : 'Lifecycle Methods'
                }
                console.log('Inside React Component 
  Constructor');
          }

        static getDerivedStateFromProps(props, state) {
                console.log('Inside React Component
                        getDerivedStateFromProps');
          }

        componentDidMount(){  
                  console.log("Inside componentDidMount");
         }

        render() {
                console.log('Inside render method');
                return <div> This is the App Component </div>
        }          
  }
  ```


> Console Output for the above code:
> ![Console Output](https://dev-to-uploads.s3.amazonaws.com/i/vazd0kprobz7ya4m98ck.png)

Still With Me here? Hold on a bit 
![lets go](https://dev-to-uploads.s3.amazonaws.com/i/di4m3qatvxr3b2w2bcmb.gif)

Now, let's see the 2nd Phase of a Component's Lifecycle

### 2. 👨‍💻 **_Updating Phase:_**

* Whenever there is a _change in the state_ of the component, the component's lifecycle comes inside the Updating phase.
* Some of the methods are _common in the Mounting and Updating phase_, this is because these same methods are called again during this phase. These methods are:
 * _getDerivedStateFromProps()_, and
 * _render()_
* Including these methods, there are a total of 5 methods in the Updating phase. Let's look at them one by one

#### 1. _static getDerivedStateFromProps()_
* In the Updating phase of the component this method is called whenever the component receives new props, or whenever the _setState()_ method is called to updated the existing state.
* One thing needs to be made sure here is that there should be no HTTP requests or Ajax calls etc. be made in this method.

#### 2. _shouldComponentUpdate()_
* This method is called whenever there is a change in the state.
* It decides if the component should be re-rendered or not as it is called right before the _render()_ method when new props or state are received.
* Since it is only called when there is a change in the existing state, this method was not present in the Mounting phase.
* It takes in the _nextProps_ and _nextState_ as the function parameters, which looks like this:

> ` shouldComponentUpdate(nextProps, nextState) `

* If this method returns false, it notifies React that the update can be skipped.

#### 3. _render()_
* The functioning of the render() method in the Updating phase is same as that of in the Mounting phase.

#### 4. _getSnapshotBeforeUpdate()_
* This method is called right before any changes are going to be updated in Real DOM from virtual DOM.
* It is used to capture some information from DOM. Example: Observing the scroll position, etc.
* It is the final call to check the data with its previous state/props.
* This method will either return a value or null. Whatever the return value is, it will be passed as the 3rd parameter to the next method.

#### 5. _componentDidUpdate()_
* This is the final method of the Updating phase.
* It is called after all the changes are updated in the DOM.
* The syntax for this is as follows:

> ` componentDidUpdate(prevProps, prevState, snapShot) `

* The 3rd parameter i.e. the snapshot is the value which was returned by the _getSnapshotBeforeUpdate()_ method.

Let's see the below code to understand the Updating phase:

> Child.js:

```javascript
import React, { Component } from 'react';  
          
class Child extends Component{  
        constructor(props){  
                super(props);  
                this.state={  
                        value:'React Application'  
                }  
                console.log("Inside child constructor");  
        }  
  
        static getDerivedStateFromProps(props,state){  
                console.log("Inside child getDerivedStateFromProps");  
                return null;  
        }  
  
        componentDidMount(){  
                console.log("Inside child componentDidMount");  
         }  
  
        shouldComponentUpdate(){  
                console.log("Inside child shouldComponentUpdate");  
                return true;  
        }  
  
        getSnapshotBeforeUpdate(prevProps,prevState){  
                console.log("inside child getSnapshotBeforeUpdate");  
                return null;  
        }  
  
        componentDidUpdate(){  
                console.log("Inside child componentDidUpdate");  
        }  
  
        render(){  
                console.log("Inside child render");  
                return <div/>  
        }  
}  
  
export default LifecycleChild;
```
> App.js

```javascript
import React,{Component} from 'react';  
import Child from './Child';  
          
class App extends Component{  
        constructor(props){  
                super(props);  
                this.state={  
                        value:'React Application'  
                }  
                this.changeState = this.changeState.bind(this);  
                console.log("Inside constructor");  
        }  
  
        static getDerivedStateFromProps(props,state){  
                console.log("Inside getDerivedStateFromProps");  
                return null;  
        }  
  
        componentDidMount(){  
                console.log("Inside componentDidMount");  
        }  
  
        shouldComponentUpdate(){  
                console.log("Inside shouldComponentUpdate");  
                return true;  
        }  
  
        getSnapshotBeforeUpdate(prevProps,prevState){  
                console.log("Inside getSnapshotBeforeUpdate");  
                return null;  
        }  
  
        componentDidUpdate(){  
                console.log("Inside componentDidUpdate");  
        }  
  
        changeState = () => {   
                this.setState({  
                        value : "React Application started"  
                })  
        }  
  
        render(){  
                console.log("Inside render");  
                return(  
                        <div>  
                                <div>React Parent</div>  
                                <button onClick={this.changeState}>Click Me</button>  
                                <Child />
                        </div>  
                );  
        }  
}  
  
export default App; 
```

> Console Outputs:

> 1. During Mounting..

> ![On Mount](https://dev-to-uploads.s3.amazonaws.com/i/0yl696m8wcjigch1las2.PNG)

> 2. During Updating (On clicking the "Click Me")...

> ![On Update](https://dev-to-uploads.s3.amazonaws.com/i/w902869ahzrfaoxxydsr.PNG)

> Notice that all the console outputs are _in the order_ for all the methods as per the lifecycle. But there is a small different in calling of getSnapshotBeforeUpdate().
> For the getSnapshotBeforeUpdate() method, the child's method is called before the Parent's method. Once called, all the other Parent's methods are called.

**Note:** Even thoght we saw 5 methods for the updating phase, the most used ones are the **render()** and **componentDidUpdate()**, out of which **render()** is the only method which is mandatory.

### 3. 🥂 **_Unmounting Phase_**
* The React component enters this phase after going through the Updating phase, when the component is removed from the DOM.
* This phase as only 1 method, which is:

#### _componentWillUnmount()_
* This method is called just before the Component is _removed from the DOM_. This removal can be _unmounting or being destroyed_.
* We need to make sure of one thing that is, the _setState()_ method should never be called inside this method.
* The reason for this is, the _componentWillUnmount()_ method is the last stage of the lifecycle of any React Component, once it is unmounted it will never be mounted again. And the _setState()_ method re-renders the contents on the DOM, so it will not be possible.
* _Usage:_ This method can be used for _Clean up_ process. For example, closing any open connections, or cancelling any network requests or removing any event handlers, etc.

### Summary:
So during the lifecycle of any React Component, it goes through different phases, these phases are **Mounting**, **Updating** and **Unmounting** phase. There is another phase called as **Error Handling** phase which also contains two methods: `getDerivedStateFromError()` and `componentDidCatch()`.

> Thanks for Reading.. 🔚