Components of React lifecycle

29 Aug 2022
Intermediate
2.31K Views

Each component of React has various lifecycle methods. You can override these methods to execute code at specific durations in the process. The corresponding lifecycle methods can be monitored and controlled during its 3 key phases. These phases are namely Mounting, Updating, and Unmounting. If you are learning to React to become a React developer, you need to know in-depth about these phases.

React and other popular frameworks such as Angular provides the developers a set of predefined functions or events that if the current rendering phase is invoked around specific events in the lifetime of the component and the developers are needed to override the respective functions with desired logic to execute accordingly.

Let’s now delve into the details of each of these phases: 

How to understand a component’s lifecycle methods in ReactJS

Mounting: 

Mounting implies the placement of elements inside the DOM. The corresponding methods are called in the below order whenever an instance of a component is created and placed within the DOM.

  • render()

  • constructor()

  • static getDerivedStateFromProps()

  • componentDidMount()

render:

Out of these 4 methods, the render() method is always required and it will be called always. The other three methods are optional; they are called only if you define them. When the render() method is called, it must inspect this. props and this. state. Subsequently,

The render() method represents the HTML and the behavior that how it will look into the browser, and it consists set of elements along with arguments as given below.

t returns any one of the below types:

React elements: These elements are usually created through JSX. For instance, <MyComponent /> and<div /> are React elements that guide React to deliver a DOM node. Alternatively, I can guide React to deliver an additional user-defined component.

Portals: This allows you to provide children with a diverse DOM subtree.

Arrays and fragments: This allows you to return multiple elements from the render. 

Booleans or null: It renders no output.  These elements usually exist to support return test && <Child /> pattern, in which test is Boolean.

String and numbers: They are delivered in form of text nodes in the DOM.

constructor:

There is no need to implement a constructor() for your React component if you don’t bind methods and don’t initialize the state.

This method is called prior to all, whenever the component gets initiated. It is the usual place to establish the initial state as well as other initial values.

It is known that this method is called along with the props, in form of arguments. You must always begin by calling the super(props) prior to any other components. The same will set up the parent's constructor method as well as enable the component to take over methods from its parent i.e. React. Component.

getDerivedStateFromProps:

Before you render the element(s) within the DOM, you need to call the getDerivedStateFromProps() method. It is the usual place to assign value to the state object depending on the initial props. This method accepts the state as an argument. Moreover, it returns an object with some modifications to the state.

componentDidMount:

This method is called immediately after the component is rendered. It enables you to execute the statements that need that the components must be inserted in the DOM. If you want to load data from some remote endpoint then this is a decent place to initiate the network request.

This lifecycle function is quite popular or frequently used because we need to have network calls on initial phasis, initiate some default values to the state, call the internal function of the component, and so on.

Updating:

The subsequent phase in the lifecycle is the instant when a component gets updated. With the modifications to state or prop, an update can be created. React comes with 5 built-in methods which get called. The corresponding methods are called in the below order whenever a component gets updated:

  • render()

  • static getDerivedStateFromProps()

  • shouldComponentUpdate()

  • getSnapshotBeforeUpdate()

  • componentDidUpdate()

render:

This method is inevitable and always be called. Other methods are optional and will be called when you define them. When a component gets updated, this method will be called. It updates the HTML into the DOM with some modifications. 

An important thing to be noticed about the render function is that the render function should be implemented as a pure function which means, it does not attempt to use setStateor to interact with the external APIs.

getDerivedStateFromProps:

After a component gets updated, this is the first method that is called. It is considered as the usual place to assign value to the state object depending on the initial props.

shouldComponentUpdate:

In this () method, you can return a Boolean value that mentions either React must continue with updating process or not. Its default value is true.

getSnapshotBeforeUpdate:

Prior to the update, you gain access to the state and props through this method. It implies that even after the update is completed, you can analyze the values set before the update. When you use the getSnapshotBeforeUpdate() method, you must also use the componentDidUpdate() method, else there will be an error.

componentDidUpdate:

The calling to this method happens after the component gets updated in the DOM. You can use this method as an opportunity to work on the DOM whenever the component gets updated. It facilitates network requests till you compare the current props to the previous ones.

When the component is still mounting, it is rendered with some color, say red. After it gets mounted, a timer alters the state, and the color changes. This action ultimately triggers the update phase. Because this component is implemented with a componentDidUpdate method, the method implements and writes a message inside the vacant DIV element:

Unmounting: 

When a component gets discarded from the DOM, this method is called. It is one of the built-in React methods that are being called when there is unmounting of a component. Moreover, it carries out essential cleanup like canceling network requests, invalidating timers, or clearing up any subscriptions which were previously made in componentDidMount().

Error Handling: 

In the course of react js certification, you also need to learn how to handle the error. The error handling is therefore an important part of the React lifecycle. Within a lifecycle method or during rendering or within the constructor of a child component, an error may occur sometimes. Under such situations, this method is called. The corresponding methods are: 

  • static getDerivedStateFromError()

  • componentDidCatch()

static getDerivedStateFromError():

This method of error handling is called upon after an error is raised by a successor component. Moreover, it obtains the error that was delivered as a parameter and must return a value for updating the state.

componentDidCatch(): 

The componentDidCatch() method is called upon after an error is delivered by a descendant component. It accepts the following parameters:

  1. error: The error which was thrown.

  2. info – It is an object having a component stack key that contains the details about which component raised the error.

Since the componentDidCatch() is called through the “commit” phase, the side-effects are allowed. 

Summary

In this article, we have discussed in brief about all the component lifecycle methods and each of them represents individual action whenever it happen during the component rendering cycle, without it, React feels implete as it serves the major purpose of the component.

The end-users can interact with the application and receive the right amount of the feedback and information in return whenever it happen. It makes interactivity more engaging for the end-users and results better usability. thus the React lifecycle makes component a complete package.

Also, Read this Awesome Article - 

Learn to Crack Your Technical Interview

Accept cookies & close this