How to initialize states without constructor in React.js?

What is a Lifecycle Method in React.js? »

If you remember, I told you that there are multiple ways of initializing states in a React component. You’ve already seen one of the ways, which was like this (inside the constructor method):

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

There’s an alternate way of doing the same exact thing (to initialize states). You can remove the constructor function altogether and initialize states as follows:

state = {hrs: ’’, hasError: false};

Notice that there’s no this.state here, only state. You use this. accessor only when you’re trying to access an object (which belongs to a class) from a method defined inside that class itself. For instance, this.state was being used because state is an object that belongs to the App class. Now, class App has a method called constructor, inside of which you’re trying to access the object. That’s why you used this. accessor. Now, if you don’t use a constructor, you can use the state object directly. This is how your index.js file should look like after removing the constructor function and defining the states directly inside the component:

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

class App extends React.Component {

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

Leave a Comment