Andy Tran

Component Lifecycle Hooks of React JS

by | Aug 21, 2021 | Web Dev

What is React JS and Its Component Lifecycle Hooks

React JS is a JavaScript library for building fast and interactive user interfaces. It was developed at Facebook in 2011 and is the most popular JavaScript library for building user interfaces, validated by the Google Trend chart below.

The Blue line depicts React JS, Red is for Angular and Yellow stands for Vue JS. All these three technologies are used to build interactive user interfaces.

With React JS, we focus on building the Components of a website page. A Component is a piece of User Interface, the figure below gives an example of four components.

While building an application with React JS, we build a bunch of independent, isolated and reusable components, and then combine them to build complex user interfaces. So every react application is nothing but a tree of Components. Lets visualize the tree for the above given UI.

You may be thinking about what the “App” Component at the top refers to. Every react application has one Component which is called a “root Component” . This component represents the entire application and contains other components as a child.

What do these components look like in terms of code? Component is a JavaScript Class that contains state and render method, where state is an object type variable which contains the data that we need to display when the component gets rendered. And the render method is responsible for what the Application UI should look like.

Example :

class Navbar extends Component {
state = { };
render( ) { }
}

The output of the render method is a React Element. React Element is a simple JavaScript Object that maps with DOM Element. The interesting part of react is that it creates a copy of the DOM Element in memory, that’s why React Element is also known as Virtual DOM. Virtual DOM is cheap to create when compared to “Real” DOM Element. So whenever there is a change in state (Data) of any component in Application, react creates a new React Element and compares it with the “Real” DOM Element to figure out what has been changed, and it only updates that part in “Real” DOM. This makes React JS a lightweight library which makes sure that the React Element is in sync with “Real” DOM Element during a change of state.

In React JS, Components go through four phases during their life cycle. These phases are Initialization, Mounting, Updation, and Unmounting. There are a few methods in each phase that get called automatically when a component is in that particular phase (note that these methods are called in sequence i.e. the next method gets called only after the previous one has finished execution). By having knowledge about these phases, we can control and manipulate the components throughout their lifecycle.

In this section we will explore the four phases in detail.

a. Initialization Phase
Here, just the setup for props and state takes place.

b. Mounting Phase
Here, the instance of the component is created and inserted into the DOM. During this phase we can do certain activities by overriding methods which are available in this phase; they are also known as life cycle hooks. It’s like there is a hook in our hand and we are controlling the boat (components) with that hook.

The Mounting Phase has 3 life cycle hooks:

  • componentWillMount
  • Render
  • componentDidMount

componentWillMount is called before a component mounts or render method is called. As it is called before the render method, we can use it to set the default configuration for a component.

Render is called after componentWillMount or constructor method, it is understood by the name of the method that the rendering of component on screen is done.

componentDidMount is the best place to make an API call. Until this step, the components are mounted and rendered on screen, so the only thing we need is data for which we can call our API and have that displayed on screen.

Example of using componentDidMount

class Product extends Component {
state = { };
componentDidMount ( ) {
//Get data from API here…
}
render( ) { }
}

c. Updation Phase
Working with API means continuous changes in data, hence the component needs to be re-rendered. The updation phase is where we can control when and how the updation should take place.

The Updation Phase has 5 life cycle hooks:

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • Render
  • componentDidMount

Let’s discuss the first 3 methods, the rest 2 are already covered in the previous section.

componentWillReceiveProps is used to compare “new props” with “old props” to see if anything has changed or not, before we use props to do anything. What are props? In ReactJs we call an object containing data as “props”. We use props to pass data from one component to another component. Props can change anytime. After handling the changes, the component will be re-render. For example, if the price of a product changes, you can use this method to change the price easily.

componentWillReceiveProps (nextProps) {
if ( this.props.price !== nextProps.price ) {
this.setState( { price : nextProps.price } );
}
}

shouldComponentUpdate is called before the re-rendering of components after receiving the new Props. What if the changed data does not affect the component? For this, the shouldComponentUpdate method comes into picture. It tells ReactJs if there is a need to re-render a particular component or not. It returns a boolean value, True means needs re-rendering while False means that there is no need. This is the best place to improve the performance of the page by controlling unnecessary re-rendering of the components.

Example

shouldComponentUpdate (nextProps, nextState) {
// conditions & return true or false.
}

componentWillUpdate is called when we need to do non-React work (something that is outside of react architecture) like checking the window size of the system on which the page is going to be rendered, and other such things. It is called when it is confirmed that the component will be rendered. This can be used to show some loading animation before the page is rendered.

Example

componentWillUpdate (nextProps, nextState) {
// called loading animation function.
}

d. Unmounting Phase

This Phase is called when a component is being removed from the DOM.

componentWillUnmount is called just before the component is removed from DOM. Here we can remove event listeners, cancel network requests and other similar steps.

Now that you know about React JS, how it works and core concepts like component life cycle, what are you waiting for? The Facebook team is working hard to keep the React community updated, you can learn more about React JS’ basic & advanced topics from React Docs.

Keep learning!

Google Trend URL :

https://trends.google.com/trends/explore?q=%2Fm%2F012l1vxv,%2Fg%2F11c0vmgx5d,%2Fg%2F11c6w0ddw9