An In-Depth Look at the React Lifecycle Methods
Tags: react, javascript, webdev, tutorial
Published: 2021-12-30 14:57:35

**What is react component lifecycle?**

Humans have to go through three stages of life: birth, grow and death to complete their lifecycle. To govern whatever events are taking place on a website, a React component also has a lifecycle, and like humans, a React component’s lifecycle comprises three phases to have better control over the components as well as to manipulate them. 

**What are the three phases of a React component’s lifecycle?**

A component must go through three stages of life to complete its lifecycle: **mounting**, **updating** and **unmounting**. Each stage of a lifecycle offers lifecycle methods. In this blog, I will explain the purpose of these methods and will demonstrate how to implement them by writing a code for each.

**Mounting**

Mounting is the initial phase in the lifecycle of a React component, and it is invoked when the component has to be placed into the Document Object Model (DOM) and displayed for the first time on the webpage. 

Mounting provides us with four lifecycle methods: 
- constructor()
- getDerivedStateFromProps()
- render()
- componentDidMount()

**Constructor()**
 
The constructor() method is triggered when the component is created as well as when a state or any variable needs to be defined. We can also use the constructor() method to bind event handlers to the class instance. 
 
The following shows an example of how to use a constructor() method:
 
**Input:**

![constructor()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/etxbhto41wry25shhzfj.png)

**Output:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fc97nd102brbcxq42pc3.png)

The super() is used to access all the methods of the parent class. The constructor() method only initializes the state hence why we wrote the increment() function outside the constructor since it carries the setState() method that updates the state (the count gets incremented by 1 every time the button is clicked) when the button ‘click’ is clicked.

**getDerivedStateFromProps()**

This method is a static method used when the state depends on the props of the components. It takes updated props and the current state as arguments and returns either null or an object that has the updated state of the component. The following shows an example of how to use a getDerivedStateFromProps() method:

**Input:**
![getDerivedStateFromProps()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rmka7cnnv5s27yxrdh3t.png)
 
A prop is sent from the parent class ‘App’ to the child class ‘Child’. With the help of a constructor(), a state is initialized. The getDerivedStateFromProps() receives the prop from the parent class as a parameter and compares the message in this.state with the message in prop. As a result, the state gets updated as the condition in the if statement is false. A null would have been returned, however, if the condition was true and we would have seen the message ‘Hi Everyone’ on the UI.

**render()**

Out of all lifecycle methods, the render() method is the only one that must be used. This is the mechanism responsible for delivering HTML to the DOM. In other words, it describes the browser how the content should be rendered on the UI.

I haven’t provided any examples as we have already seen how to use this method in the above two examples.

**componentDidMount()**

This method is called after the render() method. After the React component is mounted (i.e., is created and inserted) into the DOM, the componentDidMount() gets invoked. This method is usually called to implement APIs. The following shows an example of how to use a componentDidMount() method:

**Input:**

![componentDidMount()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a35z0jaokdh6z03wlgxc.png)

**Output 1:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e9ck6dt3d7bws6uhl2jb.png)
 
**Output 2:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vklr47rbgrj66hvla5az.png)

The componentDidMount() is invoked after the constructor initializes the state and with help of the render() method, the message Year 2021 gets rendered. Then  the componentDidMount() gets called  to re-render the message.


**Updating**

The second phase of a React component’s lifecycle gets triggered when the components need to get re-rendered due to changes in props or in state.

Updating provides us with five lifecycle methods:
- getDerivedStateFromProps()
- shouldComponentUpdate()
- render()
- getSnapshotBeforeUpdate()
- componentDidUpdate()

Out of the five methods, I will explain **shouldComponentUpdate()**, **getSnapshotBeforeUpdate()** and **componentDidUpdate()** as the other two methods(**render()** and **getDerivedStateFromProps()**) has already been discussed in the above sections.

**shouldComponentUpdate()**
 
This method informs React whether or not to update and re-render the component. It produces a Boolean result indicating whether or not to update, with true being the default. This approach is quite effective for improving performance by minimizing the need to constantly re-render components.

You may create your own logic to verify whether the component should update or not depending on the comparison result between the previous props and the next props as well as the previous state and the next state. If the result evaluates to true the component gets updated and re-rendered. The following shows an example of how to use a shouldComponentUpdate() method:

**Input:**

![shouldComponentUpdate()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8fime3h1zyircfvcgeu0.png)

**Output:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5xhpox6i34qpy8tu4gj6.png)  

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ncmqfxa8zvojznpgww2j.png)
 
Here, I have sent a prop with a value 5 to the shouldComponentUpdate() method and inside the method I have incorporated an if statement that evaluates to true and  returns false if the count after incrementing equals to 5. This indicates that the method will not update the component if it returns false and this can be seen in the output - the value 5 did not get rendered on the console of Chrome DevTools as it returned false.

**getSnapshotBeforeUpdate**

This methods receives the previous props and the previous state as parameters and is invoked right before the DOM gets rendered. The getSnapshotBeforeUpdate() allows your component to capture certain information from the DOM before it gets updated. It returns either a null or a value and this values gets passed as an argument to the next method we will be talking about. 

The following shows an example of how to use a getSnapshotBeforeUpdate() method:

**Input:**

![getSnapshotBeforeUpdate()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v6b54fqg6uzu4magb9zj.png)

**Output:**

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l77amq1imol3mtpz4ay6.png)
 
**componentDidUpdate()**

Once the update is complete, this function is called. It accepts as input the previous props, previous state, and a parameter from the getSnapshotBeforeUpdate(). If we need to change anything in the component after the update we use the componentDidUpdate() method.

I have not shown any code for the componentDidUpdate() as I have implemented this method in the previous example.


**Unmounting**

This is the last stage of a React component lifecycle and this get invoked when the component needs to be removed from the DOM.

Unmounting provides us with one lifecycle method: 
- componentWillUnmount()


**componentWillUnmount()**

When there is no matching in the element tree for a component, it enters the unmount phase. The componentWillUnmount() gets called just before the component is deleted from the real DOM. Along with the removal of this component from the DOM tree, all of its children are also automatically deleted.

The following shows an example of how to use a componentWillUnmount() method:
Input:

![componentWillUnmount()](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0s08dn4t1pezaacklp5h.png)

Output:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvj3qp7tvopvlnqi4bu5.png)

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1rmwz9qmwscjkoeffjzc.png)
 
The componentWillUnmount() pops a message on the alert box before hiding the second message when the this.state.show becomes true after clicking the button. This shows that the method gets invoked before deleting any components.


Well, that’s all! I hope you have a better grasp of what React lifecycle methods and how they operate after going through this blog and the practical examples.

Catch you later!