DEV Community

Shafia Rahman Chowdhury
Shafia Rahman Chowdhury

Posted on

An In-Depth Look at the React Lifecycle Methods

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()

Output:

Image description

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()

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()

Output 1:

Image description

Output 2:

Image description

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()

Output:

Image description

Image description

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()

Output:

Image description

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()

Output:

Image description

Image description

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!

Latest comments (4)

Collapse
 
ayobami profile image
David

Thank you.

Collapse
 
shafia profile image
Shafia Rahman Chowdhury

My pleasure. I hope that it was a helpful post.

Collapse
 
pcelac profile image
Aleks

Too bad that class Components are so 2020, functinal Components are now prefered way to go.

Collapse
 
shafia profile image
Shafia Rahman Chowdhury

Yeah, I have also used functional components so far in my projects but I thought it would be easier for the beginners to understand the lifecycle methods better if I implement them using class components on my demonstrations rather than using functional components.

I have heard that the class components will get deprecated because of the hooks, but I have also heard that you cannot access all the lifecycle methods using hooks. Why is it getting removed then? Any thoughts?