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}; }
Table of Content
- What is a Lifecycle Method in React.js?
- How to load data using Lifecycle Methods in React.js?
- How to initialize states without constructor in React.js?
- How to pass state as props in React.js?
- How to determine day or night in React.js?
- How to display conditional images in a component in React.js?
- How do compiled code looks like in React.js?
- How to use Config Objects in components in React.js?
- How to show a loading screen when components are loaded in React.js?
- How to specify Default Props in React.js?