Methods of React Lifecycle

In React whenever a component is created or inserted into the DOM the following methods are called:

  • constructor()
  • componentWillMount()
  • render()
  • componentDidMount()
  • componentWillUnmount()

render()

render() is the most used method in the React component, and this is the only method that is required in class components. One important thing to note here is render() must return some value. It can either be JSX or HTML element or null, but it must return something. render() method is called by default whenever a component file is called.

Note: you should not use setState() inside render() because setState() changes the value of the state and as the setState() changes the component will re-render itself which will happen recursively, and the app will break

class App extends React.Component {

render()
{
    return(
        <div>
            <h1> HELLO WORLD </h1>
        </div>
    )
}

}

“`

constructor()

A constructor is called before the React component gets mounted. The constructor is mostly used for initializing state and binding functions. Whenever you implement constructor, you should always call super(props) before any other statement.Otherwise this.props will be undefined.

Note: If you don’t need to initialize state or don’t need to bind the function, you can skip implementing constructor.


class App extends React.Component 
{
    constructor(props)
    {
        super(props);
        this.state = {
            counter: 0,
        }
    }

    render()
    {
        return(
            <div>
                <h1> Counter </h1>
                <h3> {this.state.counter} </h3>
            </div>
        )
    }
}

componentWillMount()

componentWillMount() is the least used method in the whole React lifecycle. This method is called just before rendering any component or HTML elements. Although it is not good to use, you can use this method to initialize some variables, objects, or API libraries. A practical example could be getting user location and saving it to be used in the App when it is going to render.

componentDidMount()

This method is called after rendering of the page(when Component has finally finished mounting the DOM).componentDidMount() is an ideal pace where you can call your setState() method to change the state of your app component and render() the updated data. There are many ways where you can use this method like:

  • Using componentDidMount for AJAX requests.
  • Setup event listeners because the data is already mounted.
  • Fetch the data from an API and then use it in setState
  • Setup third-party libraries that depend on the DOM.

In the example below I have simulated, and API calls with setInterval()which will refresh data every 5 seconds

import React from 'react';
import './App.css';

class App extends React.Component 
{
    constructor(props)
    {
        super(props);
        this.state = {
            counter: 0,
        }
    }

    getDataFromAPI()
    {
        setInterval(() => {
            this.setState({
                counter: this.state.counter+1
            })
        }, 5000);
    }

    componentDidMount()
    {
        this.getDataFromAPI();
    }

    render()
    {
        return(
            <div className="App">
                <h1> Counter </h1>
                <p> {this.state.counter} </p>
            </div>
        )
    }
}

export default App;

componentWillUnmount()

This is the last method that is called whenever a component is removed from DOM i.e., componentWillUnmount() is called whenever the component is destroyed. This method is used for cleaning up anything regarding the component.

Note: you should never use setState() method in componentWillUnmount()because the component will never be re-render.

class App extends React.Component 
{
    constructor(props)
    {
        super(props);
        this.state = {
            counter: 0,
            toggle: true,
        }
    }

    componentDidMount()
    {
        setInterval(() => {
            this.setState({
                counter: this.state.counter+1
            })
        }, 10);
    }


    render()
    {
        return(
            <div className="App">
                <h1> Counter </h1>
                {
                this.state.toggle ? <AppUnmount value = {this.state.counter} /> : null
                }
                <button  onClick={() => { 
                    this.setState( { toggle : ! this.state.toggle } )
                    } }> Click Here </button>
            </div>
        )
    }
}

class AppUnmount extends React.Component
{
    componentWillUnmount()
    {
        var msg = "Last value before component Unmount " + this.props.value;
        alert(msg);

    }
    render()
    {
        return(
            <div className="App">
                <p> {this.props.value} </p>
            </div>
        )
    }
}

Sharing is caring!

Leave a Comment

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

shares
Scroll to Top