How to initialize default state object in constructor in a component in React.js?

How to use states in React.js »

Once you have the constructor function defined, you can define state variable values there (assign values to initialize object). Here, the only relevant property you may want to define is the hrs variable. All the variable are defined inside this.state object. For instance:

this.state = {hrs: };

Whenever you initialize a property in a state, you need to assign it to a reasonable and valid value, for example:

this.state = {hrs: ‘’};

Right now you don’t know what the value of hrs is going to be, that’s why a default ‘’ string or null value is assigned instead, until the actual value is updated.

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

class App extends React.Component {
    constructor(props){
       super(props);
       this.state = {hrs: ''};

    }

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

   
const getTime = () => {
           setTimeout(() => {
               const hours = getHours().toString(); console.log(hours);
               return hours;
           },
           3000);
       }
       return <div>Current hour is: </div>
    }
}

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

Leave a Comment