Component Life Cycle in React JS

The React components follows the life cycle which includes various methods to be overridden. The React Component Life Cycle is divided into 4 phases:

  • Initial Phase
  • Mounting Phase
  • Update Phase
  • Unmounting Phase

Initial Phase in React Component

 The initial phase for the React Component allows to initialize the default properties and state values. The usage of constructor in the React Component helps in defining the initial values for props and state.

getInitialState() is used to define the default value of state using this.state

getDefaultProps() is used to define the default value of props using this.props

The methods getInitialState() and getDefaultProps()are invoked before the creation of the React Component

Mounting Phase in React Component

Mounting is related to the creation of the component in the DOM Structure. The below given methods are invoked in the same sequence when an instance of component is created and inserted in the DOM Structure.

  • constructor( ) : The React Component Constructor intialiaze with default values for props and state
  • static getDerivedStateFromProps() : Retrieves the props and state value
  • componentWillMount() : gets invoked before the component is rendered into the DOM 
  • render() : returns the single root HTML node element 
  • componentDidMount() : gets invoked after the component is rendered into the DOM 

Updating Phase in React Component

The updating is related with the update of the component which could have the change in props or state in the component. The component invokes the below given methods in the same sequence when re-rendered it for the update in the DOM Structure.

  • componentWillRecieveProps() : gets invoked when a component receives new props.  this.setState() should be called while updating the state in response to prop changes
  • static getDerivedStateFromProps() : Retrieves the props and state value
  • shouldComponentUpdate() : gets invoked when a components receives any updates to be rendered to the DOM, else will be skipped
  • componentWillUpdate(): gets invoked before the component is rendered into the DOM and  shouldComponentUpdate() returns true
  • render() : validatesthis.props and this.state and could return (React elements, Arrays and fragments, Booleans or null, String and Number) . If If shouldComponentUpdate() returns false, render() is invoked again to ensure component state is maintained and display the content correctly
  • componentDidUpdate() : gets invoked after the component is rendered into the DOM

Unmounting Phase in React Component

Unmounting is related to the removal of the component from the DOM Structure.

  • componentWillUnmount() : gets invoked before the component is destroyed / unmounted completely. The componentWillUnmount() performs the clean up activities like removing events, removing timers, cancelling requests or cleaning DOM elements

Exception Handling in Component: The error occurs while rendering the component or in the constructor of the child component are managed.

  • static getDerivedStateFromError()
  • componentDidCatch()

The below given diagram depicts the phases used by React and the methods getting invoked in each phase. 

Diagram Reference Link: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/

Component Life cycle Diagram

Render Phase: The grey area depicts the Render Phase used by React to perform the below actions

  • Render Phase can be paused by React
  • Render Phase can be aborted by React
  • Render Phase can be restarted by React

Commit Phase: The white area depicts the Commit Phase used by React to perform the below actions

  • allows React to work with the DOM Structure
  • allows React to run the side effects
  • allows React to update with the DOM Structure

render method in the class component

The component uses the render() which is only required methods to be implemented. The render function does not modify the state of the component and returns the same output for each invocation. The invocation of render() examines the this.props and this.state and performs the below given actions

  • React elements </div> or custom components created using JSX to be rendered to the DOM node in the Structure.
  • allows to return multiple elements including arrays or fragments
  • allows to render child components into different sub tree in the DOM Structure.
  • renders the strings and numbers as text node in the DOM Structure
  • Does not render Boolean or null values.

Component Reference Link : https://reactjs.org/docs/react-component.html#render


How to use Constructor in React component

The blog provides the usage of Constructor in React Application. The concept of Constructor in React is similar to what we implement in other languages like C++ , Java.

What is a Constructor in React ?

The Constructor can be defined as given below

  • The constructor is used to initialize an object’s state
  • The constructor is invoked when an object is created in the class
  • The constructor is called in React when a component is mounted
  • The constructor is called using super(props)
  • this.props remains undefined if super(props) is not called in the class

How React uses constructor ?

  • Initialize the local state by assigning an object to this.state
  • Binds Event handler methods to an instance

How State should be initialized in the constructor() ?

  • The Constructor should not be called this.setState() in the constructor
  • We should use this.state to initialize the local state in the constructor

When constructor should be used in React Component ?

Usage of Constructor is not mandate for all the React Component. Constructor helps to initialize the object state before it is actually being accessed / modified. That is , when we need to set a object property or to access the object local state , then constructor should be called using super(props). 

If the super(props) is not defined in the constructor and program try to access the object value using this.props , then React will throw the error ->  ‘this’ is not allowed before super().

class App extends Component {  
    constructor(props){  
        // wrong assignment, super(props) is not defined
        this.siteName = "www.oracleappshelp.com";  
    }  
    render () {  
        return (  
            <p> Site Name : { this.props.siteName }</p>  
        );  
    }  
}
class App extends Component {  
    constructor(props){ 
      // correct  assignment                
		super(props);
        this.siteName = "www.oracleappshelp.com"; 
    }  
    render () {  
        return (  
            <p> Site Name : { this.props.siteName }</p>  
        );  
    }  
}

this.props will be undefined in the Cosntructor if super(props) is not called.

Use Constructor to bind functions in React Component

The constructor in React Component is useful when we need to bind functions as per below given example . The button clickSubmit is binded using this

constructor(props) {
  super(props);
  this.state = { count: 0 };
  this.clickSubmit = this.clickSubmit.bind(this);
}