React Lifecycle Methods for Class Components

Learn via video courses

Overview

The web apps made with React comprise components. Components are nothing but individual blocks of code that are put together. We can think of these components as the bricks which are cemented together to create a structure. These components have a lifecycle and react life cycle methods are a series of events that happen throughout this lifecycle.

Introduction

In 2018, react hooks were introduced with the rise of the functional components, these hooks provided a simple and preferred way for handling state.

Before 2018, all the react code was written with class-based components. All these class-based components used react life cycle methods for state management.

Class components rely on life cycle methods for performing tasks such as state management, and calling external APIs. To a beginner, these can look complex.

React hooks rely on these methods in the background and give the developers an abstract way to manage state, call APIs, etc. The knowledge of react life cycle methods is essential to understand the concept behind the hooks and it makes it easy for the developer to write better code.

Prerequisites

Since we are dealing with react life cycle methods, you should be familiar with the basics of React.

Along with the basics, you should know the difference between a class-based component and a functional component.

Knowledge of state in react is also required to understand how these lifecycle methods work.

What is React Component Lifecycle?

The lifecycle of a react component can be broken down into four major steps

  1. Mounting
  2. Updating
  3. Unmounting
  4. Error Handling

An analogy of human life can be used to better describe these steps.

  • Mounting is when the child comes into the world 👶
  • Updating is when the child grows 💪
  • Unmounting is when the child dies ⚰️

In the mounting phase, the component is inserted into the DOM along with various react internals.

Once the component is inserted into the DOM it needs to be updated to keep it functional. All these updates happen in the update state.

In the unmounting phase, which is the final phase, the component is removed from the DOM.

React components can also go through an error-handling phase which occurs when there is some bug.

flow-of-react-life-cycle-methods

It is not a strict requirement that a react component should go through every phase of the lifecycle. There can be components that are mounted and then unmounted without any updates.

What are React Lifecycle Methods?

We discussed the react life cycle phases. Each of these phases has lifecycle methods that we can override to execute code at specified times during the process. These methods are known as "component lifecycle methods".

Mounting Lifecycle Methods

In the mounting phase, the react component is created and added to the DOM.

flow-of-mounting-phase

Let's look at the various functions which we can leverage in the mounting phase.

constructor()

A constructor is a function that is automatically called when an object of that class is created.

In react, the constructor function is called before the component is mounted.

Let's look at an example :

The constructor function is used to :

  • Initialize local state or any other third-party libraries.
  • Binding event handlers to the instance.

Some points to keep in mind about the constructor :

  • Every component need not include a constructor.
  • To set property or use 'this' we need to call super() within the constructor.

To learn more about constructors refer to official-react-docs

static getDerivedStateFromProps()

static getDerivedStateFromProps() is a react life cycle method that is designed to replace componentWillReceiveProps.

getDerivedStateFromProps is invoked just before calling the render method, it happens both on initial and subsequent mount. This method should return an object to update the state or null to update nothing.

The main purpose of this method is to make sure that the state and props are in sync.

static getDerivedStateFromProps() takes in props and state as arguments and returns an object to update the state.

If we don't want to update the state then we can return null

Here is a simple code example to show how this method works :

Output :

Since getDerivedStateFromProps run before the render method, so it updates the state to {money : 1000}.

When to use static getDerivedStateFromProps ?

The example we used does not represent the correct way to use this method however it is enough to understand the concept.

The method name getDerivedStateFromProps is made up of five words :
get-derived-state-from-props, this means that this method allows a component to change its internal state in response to a change in props.

render()

Render function is called after the static getDerivedStateFromProps method. This method is required in a class component.

To render elements to the DOM we can return JSX inside of the render method.

The render method should be pure, we cannot use setState or interact with external APIs.

componentDidMount()

Once the render method is called, the component is inserted into the DOM and then the componentDidMount() method is called.

This method is the place where you update your state and call external APIs.

Suppose we have a simple react component :

Output :

Now let's update the state using the componentDidMount() method. So our code will look like this

Output :

In this code, we have created a setTimeout() method in the componentDidMount() method which will update the state after 2 seconds. When you run this code, first it will show Old heading then after 2 seconds it will show New heading!!!.

componentDidMount() is the perfect place to make state updates and also call external APIs.

Updating Lifecycle Methods

In React the component is rerendered whenever a change is made to the state or the props of that component. This rerendering of the element is called updating.

flow-of-updating-phase

Here are the methods that are called when a component needs to be updated :

static getDerivedStateFromProps()

static getDerivedStateFromProps() is the first React lifecycle method that is called in the update phase.

We have discussed this method in the mounting phase of react life cycle methods section of this article.

Let's take an example :

Output :

The reason this code gives 20 as output is because static getDerivedStateFromProps() is called before the render method and it updates the value of the state to 20.

shouldComponentUpdate()

shouldComponentUpdate() method is called after static getDerivedStateFromProps() method.

Normally, the component is updated every time a state or prop changes but the shouldComponentUpdate() method gives us control over this behavior.

This method returns a true or false value which decides whether the component will rerender or not.

Let's take an example :

In this example, MyComp will be rerendered only if the props passed to it changes.

render()

After shouldComponentUpdate() the render() method is called to update the DOM with the latest state changes.

Output :

getSnapshotBeforeUpdate()

Sometimes we need the data which was stored in the state before the rendering happened. getSnapshotBeforeUpdate() method is called right after the render() method and allows us to do that.

The getSnapshotBeforeUpdate() method stores the previous values of the state after the DOM is updated.

This method works like the version control systems like Git.

We can compare the previous state/props to the updated state/props using this method. getSnapshotBeforeUpdate() method does not work alone, the value it returns is passed on to the componentDidUpdate() method as a third parameter.

Syntax :

Let's look at an example to better understand this method :

Output :

This example contains two components : The user and App.

The "User component" takes the amount as a prop. Inside the User component, the state value is set to 2000 and it has getSnapshotBeforeUpdate() and componentDidUpdate() methods. These two methods set the prevState and current state values to two different divs.

We have called the User component inside the App component and passed a value of 1000 to it. So when the code runs we get the output as

Then after that, the output changes to

The reason behind this is, initially we have set the state value to 2000 inside the User component, so the prevState value will be 2000. But after rendering the value of prevState changes to 1000 which is also the value of the current state.

To completely understand getSnapshotBeforeUpdate() we have to learn about the componentDidUpdate() method.

componentDidUpdate()

componentDidUpdate() method is called after getSnapshotBeforeUpdate(). This method receives two arguments prevProps and prevState. We can pass a third argument with the name snapshot which is returned from getSnapshotBeforeUpdate().

A common use case of this method is to make API calls whenever the component updates. We can first check if there is any state change and then make the API call inside this function.

One thing to note here is that componentDidUpdate() will not be called if shouldComponentUpdate() returns false.

Unmounting Lifecycle Method

These are the methods that will be invoked when the component reached its unmounting phase.

flow-of-unmounting-phase

componentWillUnmount()

This method is called just before the component is unmounted or destroyed. Unmounting is simply removing the component from the DOM so that we cannot modify its state or rerender it.

Suppose we have a click-me button on the Home page. When the user moves on to a new page then this component is of no use. So at that time, it should be unmounted.

Since it is called just before unmounting, it is a perfect place to perform any necessary cleanup such as network requests or timers.

Let's take a simple example where we put an event listener inside the componentDidMount() method and then remove that event listener inside the componentWillUnmount() method.

Error Handling Lifecycle Methods

These methods are our saviors in times of code emergency. Code emergency is a term I made up just now to make errors and bugs sound fancy.

To deal with errors, React has a concept of Error Boundaries. React components called error borders can catch JavaScript failures anywhere in the component tree of a child component, log those errors, and display a fallback user interface in place of the component tree that crashed.

Error Boundaries work like a catch statement but for components.

When does a component become an error boundary ? A class component becomes an error boundary if it defines either or both static getDerivedStateFromError() and componentDidCatch() We will learn more about these methods.

static getDerivedStateFromError()

static getDerivedStateFromError() is called when a component encounters an error. This method enables us to handle errors in the application.

First, this method is invoked with the error parameter supplied as an input. The component's state is updated using whatever value is returned by this method.

Here is how we use the static getDerivedStateFromError() method in Error Boundaries

componentDidCatch()

componentDidCatch() method works similar to static getDerivedStateFromError() method. It is called after an error in any child component occurs. Along with the thrown error, it is passed one more argument which represents more information about the error.

componentDidCatch() method allows for side effects unlike static getDerivedStateFromError() method. This means that you can send the error information to some external service inside of componentDidCatch().

This is how to use componentDidCatch()

Conclusion

In this article, we have learned a lot about react life cycle methods. Here are some key points that you can refer to

  • React life cycle methods are used in class-based components to manage the state before the introduction of functional components.
  • Lifecycle methods can be divided into four main categories :
    • Mounting
    • Updating
    • Unmounting
    • Error Handling
  • React life cycle methods can be used to override and execute our code at different phases of the component lifecycle.
  • In the Mounting phase the component is added to the DOM. It has the following functions :
    • constructor()
      • Called before the component is mounted.
    • static getDerivedStateFromProps()
      • Invoked just before calling the render method and returns an object to update state.
    • render()
      • Only required method which renders element on the website.
    • componentDidMount()
      • Called after the render method and is a suitable place to make state updates and call external APIs.
  • In the Update phase changes are made to the state or props of the component. It has the following methods :
    • static getDerivedStateFromProps()
      • The first method is called the update phase.
    • shouldComponentUpdate()
      • Called after static getDerivedStateFromProps().
      • Gives control over whether or not to rerender the component.
    • render()
      • After static getDerivedStateFromProps() and shouldComponentUpdate() this method is called.
    • getSnapshotBeforeUpdate()
      • Stores previous values of the state after the DOM is updated.
    • componentDidUpdate()
      • Called after getSnapshotBeforeUpdate().
      • Receives prevProps and prevState as arguments.
      • Value from getSnapshotBeforeUpdate() can be passed as the third argument to this method.
  • In the Unmounting phase the component is removed from the DOM. Methods in this phase are :
    • componentWillUnmount()
      • Called just before the component is unmounted.
  • Error handling phase is where we catch all the errors that occur in our application
    • static getDerivedStateFromError()
      • Called when an error occurs in the child component.
    • componentDidCatch()
      • Similar to static getDerivedStateFromProps() but it also provides extra information about the error.
      • This method also allows the call to external APIs