How the app lifecycle works in React.js?

How to use states in React.js »

You have covered quite a lot lately. Let’s try to walk-through everything in a snap so that you understand what happened from the point your app started to the point where actual hours appeared on the browser window:

  1. index.html file was loaded by the browser along with index.js, which integrated the components that would be shown inside the index.html file
  2. When index.js file is executed, a new instance of App component is created
  3. Since App component is a class based component, it calls the constructor() method. constructor() method is not required, but optional.
  4. Inside the constructor() method, super(props) is called so that existing constructor() logic inside React.Component class is preserved and not overridden by the App component class’s constructor. If you choose to define the constructor() function, then super() should also be called otherwise you’ll run into an error that demands its declaration.
  5. this.state object is created and assigned some initial values to all the different properties you want to use
  6. Next, the API request is made, or in your case, an API request is simulated by the setTimeout() method.
  7. The first time this.state is initialized, render() method is called and the return value is rendered to the browser as Current hour is: (when the value of hrs was ‘’)
  8. Next time, this.setState() is called (after 3 seconds, as set as 3000 milliseconds), render() method is called again and the older return value is overwritten as Current hour is: 2 (whatever the value of hrs is by that time).

Leave a Comment