React Component Lifecycle Methods is one topic that can trouble beginners. One reason is that there are so many of these methods. And it is not always obvious which lifecycle method should be used when.

While the introduction of React Hooks useEffect has greatly simplified the use of major lifecycle methods, these methods are still important in case you have class components.

In this post, we will look at some of the most common React Component Lifecycle Methods

1 – What are React Component Lifecycle Methods?

Before we look at actual code examples, it is important to understand what lifecycle methods are.

In a nutshell, you can think of lifecycle methods as a chain of events that occur from the birth of a component to its death. Using these methods, a developer can hook up to this events to carry out some operations during the lifecycle of the component.

The high level events every React Component goes through are Mounting, Update, and Unmounting.

2 – The Common Lifecycle Methods

Now that we have a basic idea about lifecycle methods, we can start looking at the most common ones.

Render

The render() method is an absolutely must in a React Class Component. In other words, it is mandatory.

And hence, you would find it in all React classes.

Basically, the job of the render method is to return a valid JSX or null.

The important thing about the render() method is that it should be a pure function. In other words, there should be no side-effects. Basically, this function should return the same output when the same inputs are passed to it.

Due to the above reason, we cannot use setState() within the render() method. Modifying the state should be done in other lifecycle methods.

Constructor

It might not appear so but the constructor is also a part of the overall lifecycle of a React Component. In fact, constructor is the first thing that gets called in a React Component. Even before the render() method.

A constructor is used to initialize the state and also setup the component. However, it is not mandatory.

If you want to setup some initial data in your component’s state, you should do it inside the constructor.

ComponentDidMount

Once the component has been mounted and is ready, the componentDidMount() lifecycle method comes into the picture.

Usually, this method is the best place to initiate some API Calls if you have a need to fetch some data from external sources.

You can also call the setState() method over here. This will, of course, update the state and cause a re-render of the component but it will happen before the browser updates the UI.

Of course, it is always advisable to set your initial state in the constructor and use setState() in componentDidMount() sparingly.

ComponentWillMount

The componentWillMount() is another lifecycle method which gets invoked before the rendering happens.

However, if you use it now, you will get a warning as below:

Warning: componentWillMount has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

* Move code with side effects to componentDidMount, and set initial state in the constructor.
* Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run `npx react-codemod rename-unsafe-lifecycles` in your project source folder.

Please update the following components: MyComponent

This is because this method is no longer recommended for use. In fact, if you wish to set initial state, it is advised to do so in the constructor rather than use componentWillMount().

The use of this method will reduce dramatically in the future if it has not already happened.

ComponentWillUnmount

As the name itself suggests, the componentWillUnmount() method is called just before the component is destroyed or unmounted from the DOM.

Due to this, it is an ideal place to perform any clean-up activities.

Of course, you cannot modify any state in this lifecycle method since after this point, the component will not be re-rendered. You can perform operations such as removing subscriptions, clearing cache etc in this lifecycle method.

3 – Lifecycle Methods in Action

Below is a code snippet that shows some of this component lifecycle methods in action.

import React from 'react';

class MyComponent extends React.Component {
    constructor(props) {
        super(props);
        console.log("My Component -> Constructor has been initialized");
    }

    componentWillMount() { 
        console.log("My Component -> Component about to be mounted")
    }

    componentDidMount() {
        console.log("My Component -> Component has mounted successfully")
    }

    render() {
        console.log("My Component -> Render completed successfully")
        return(
            <h1>Component Lifecycle Demo from My Component</h1>
        )
    }
}

export default MyComponent;

When we use this component in a parent component and start our server, we can visit the console view in the Developer Tools of the browser to see the order of output.

Below is the order in which the console.log statements will be printed.

CONSTRUCTOR

My Component -> Constructor has been initialized

COMPONENTWILLMOUNT

My Component -> Component about to be mounted

RENDER

My Component -> Render completed successfully

COMPONENTDIDMOUNT

My Component -> Component has mounted successfully

We have covered all the important React Component lifecycle methods. There are a few more uncommon methods that we will be covering in future posts.

However, if you are starting off with React, these methods will hold you in good stead for majority of the use-cases.

If you do have any queries or comments, please mention in the comments section below.


0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *