What is a Lifecycle Method in React.js?

What is a Lifecycle Method in React.js? »

These are the functions which you can optionally define right inside the class based components. If you choose to define these methods, they’ll be called automatically by React at certain point of the app’s lifecycle. That’s why these methods are called Lifecycle Methods.

You’ve already seen the constructor() method and the render() method. Constructor method is an optional method although the render method must be defined if you want to render some JSX from a component.

There are two more important lifecycle methods, named:

  1. componentDidMount(): It is called when your component is first shown up on the screen (or initial state object values are assigned using this.state.variablename)
  2. componentDidUpdate(): It is called every time the state object is updated using the setState() method and render() method is called again – things are re-rendered on the screen

React.js Lifecyle Methods

So, the takeout is that componentDidMount() method is called only once when you set some initial values to your state objects while on the other hand, componentDidUpdate() is called every time state object variables are changed using the setState() method, followed by render() method.

Add both the methods in the index.js file of the DayNight project as follows, to see them working in action:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {

    constructor(props){

       super(props);
       this.state = {hrs: '', hasError: false};

    const getHours = () => {
           const currentHours = new Date().getHours();
           return currentHours;
    }

   

    setTimeout(() => {
               const hours = getHours().toString();
               this.setState({hrs: hours});
       },
       3000);
    }

    componentDidMount(){
           console.log("Component got rendered!");
    }

    componentDidUpdate(){
           console.log("Component got updated!");
    }

    render(){

       if (this.state.hasError){
           return <div>An error has occurred!</div>;
       }
       return <div>Current hour is: {this.state.hrs}</div>;
    }
}

ReactDOM.render(
 <App />,
 document.querySelector('#root')  
);

Save the file, run the server, open console window in browser using Ctrl + Shift + K and this should be the flow of execution:

  1. State object is first initialized using this.state = {hrs: ”, hasError: false}; and render() method is called
  2. You see “Current hour is:” on the screen
  3. componentDidMount() is called and you see “Component got rendered!”
  4. Component gets updated again when state object is updated using the setState() method this.setState({hrs: hours});
  5. render() method is called again and “Current hour is:1” is shown on the screen
  6. componentDidUpdate() gets called and you see “Component got updated!” on the browser console window

Leave a Comment