How to initialize states using constructors in React.js?

How to use states in React.js »

The first thing you need to make sure is to initialize states when you first create your component. You also need to make sure you assign the actual data and update the app state once you have the updated data available. You can initialize the state variables with the help of a constructor method. This constructor method is not specific to React library but already available to the Javascript language. Any time a new instance of the class is created, this constructor method is automatically invoked before anything else. And that’s what makes it a very ideal location to initialize the app state.

There are other ways to initialize states, but for now you can initialize states using the constructor method only. This method takes in a parameter called “props”. You also need to call super(props) every time you call the constructor method. Now you may question yourself why do you need it?

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

class App extends React.Component {

constructor(props){
       super(props);
    }

   
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