How to load data using Lifecycle Methods in React.js?

What is a Lifecycle Method in React.js? »

In the previous section you learned that data loading must be done inside the componentDidMount() method as opposed to the constructor() function. It is not mandatory to do it like this, but it is a good community practice among good React developers.

Right now, you’re getting the current hour result from the constructor() function. You’re also setting the state properties from inside the constructor method. Now’s the time to move these two functions from the constructor to the componentDidMount() method. The index.js file should then look like:

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

class App extends React.Component {

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

    }

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

    

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

    componentDidUpdate(){
       console.log("Component got updated on the screen");
    }

    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')  
);

Now, if you look at the constructor function, it does nothing but initializes the states:

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

Leave a Comment