React Components Lifecycle

Skyforce Technologies
Skyforce Technologies
3 min readJan 1, 2021

React components lifecycle — Mounting, updating and unmounting of react class components.

In this tutorial, we will learn several react lifecycle phases which our class components goes through. We do not have any lifecycle phase for functional components. If you are new to react you can also check our previous tutorials on React Basics and React Hooks Introduction before continuing with react lifecycle.

Mounting Phase — This is the phase when the instance of a component is created and inserted into browser DOM. We have several methods gets called during this phase — constructor, render, componentDidMount

Here, constructor is the place to assign initialize state variables with default values or with props. componentDidMount is the place to make an AJAX call to an API while mounting your component. Render method renders the view we already know this. But during render, if we have any child components inside, then those components will also get mounted. Let’s see the order in which parent and child gets rendered.

Updating Phase — This is the phase when state or props of a component gets changed. We have two methods gets called during this phase — render, componentDidUpdate

In componentDidUpdate we can have our previous state and props values. And as we discussed this gets called after a state/prop update. So, if we want to perform any task based on specific state/prop variable change then we can compare old state/prop variable with the updated value and perform the task. Remember we can do this as well in the callback function of our setState method, but there we can’t access any previous state/prop after update.

Unmounting Phase — This is the phase when a component gets removed from the DOM. For example, in a shopping cart, a product item is a component inside the cart. So, when you remove a product item from your cart, it is being removed from the view DOM. That is called the unmounting phase of that product item. Here, we have a method called componentDidUnmount. And remember after unmounting the state changes because you can removing an item from the DOM tree. So, component Cart gets re-rendered, which means the component goes through updating phase after unmount.

componentDidUnmount gets called just before the component gets removed. So you can do any clean up activities here.

That’s all about class component life cycle. In the next tutorial we will be learning how to call an API from react, which we will doing using componentDidMount method as discussed in this tutorial. Hope you have enjoyed this tutorial. Thanks :)

--

--