React.js Component Lifecycle - Mounting phase


Each stateful means class based component goes through four types of lifecycle phases.

  • Mounting or Creation
  • Updating
  • Unmounting or Destroy
  • Error handling phase

React.js Component Lifecycle - Mounting phase

The methods that executes during creation lifecycle are −

  • constructor
  • componentWillMount (Only available till version 17 )
  • render
  • componentDidMount

constructor ()

  • It’s an ES6 feature and not a React provided method.
  • React uses the constructor to pass the props to parent Component extended from React library.
constructor(props){
   super( props );
}
  • Passing of props to parent Component helps us to use this.props in the component.
  • We can initialize the state for the component in constructor. Important point is we should not use setState method in constructor. Because setState is designed to update the state and not for creation of state.

    Use of setState inside constructor can result into unpredictable component or re-render of component in infinite way.

  • Example usage −
constructor(props){
   super(props);
   this.state = {
      test: ‘example’
   }
}
  • Side effects like call to web api should be avoided in constructor. Because web api calls takes time to return result and by that time constructor method will complete its execution.
  • Method binding can also be done in constructor e.g e.g. this.handleNewUser=this..handleNewUser.bind(this);>

componentWillMount

  • We can update the state here.
  • Last minute optimization can be done
  • This method is rarely used because it is placed between constructor and render. Whatever required by this time of life of component is already done by constructor or will be done by render method.
  • Logging or connection to database can be established here.
  • It’s a legacy method and React itself recommends for not using this method in new version starting with 17.

render

  • Executing render method gives React an idea of what needs to update on the actual DOM.
  • React keeps a copy of Original DOM, we call it as virtual DOM.
  • Changes happen on virtual DOM and in the end, React compares the virtual DOM with original DOM to update the latter.
  • This method structures and prepares the jsx code to return to DOM
  • Inside the render method, we can jsx code of child component.
  • So lifecycle method for child component will run at this point of time.

componentDidMount

  • Execution of this method means component is successfully mounted or created on real DOM.
  • Here we can do side effects like using timers, calling web api, adding event listeners.
  • This method gets called only once in the lifecycle of stateful component.
  • Use of setState in this method can trigger render again to update DOM.
  • We are able to do side effects inside this method because it executes only once so there will not be an infinite loop if we update the state using setState.
  • If we want to manipulate a dom node, then this method is the best place to do that.

Example of calling a web API is shown below

If you have latest node.js installed on system, below command can be used to create a React project using cmd

npx create-react-app componentdidmount-example

Name of project after create-react-app word is user specific. Use of capital letter in name of project is restricted due to npm naming conventions.

We will be using Axios for making web api calls. To install it use below command

npm install –save axios

To demonstrate this example, we used open source dummy api provided by jsonplaceholder − https://jsonplaceholder.typicode.com/users

App.js file

import React, { Component } from 'react';
import axios from 'axios'
import './App.css';
class App extends Component {
   constructor(props){
      super(props);
      this.state={
         users:{},
         isUsersLoaded:false
      }
   }
   componentDidMount(){
      axios.get('https://jsonplaceholder.typicode.com/users')
      .then(result=>{
         console.log(result);
         this.setState({users:result.data,isUsersLoaded:true});
      });
   }
   render(){
      if(!this.state.isUsersLoaded){
         return <div>Loading...</div>
      }
      return (
         <ul>
            {this.state.users.map(user => (
               <li key={user.id}>
                  {user.name}
               </li>
            ))}
         </ul>
      );
   }
}
export default App;

We used constructor to init our users and isUserLoaded flag.

ComponentDidMount lifecycle is used to get the users from the server and we updated our list once we receive it asynchronously

We showed loading text till we receive the users lists in the render lifecycle method.

The output on the browser is shown below −

Updated on: 04-Sep-2019

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements