React Component Lifecycle

All the react component goes through a lifecycle which enables you to perform a specific task at any specific time. In order to achieve that you can override the life cycle methods. Methods prefixed with will are called right before something occurs (events), and methods prefixed with did are called right after something occurs.

Let us understand all the functions in all the phases of life cycle :

setup props and state(constructor(props))

You all must be heard about the constructor . Constructors are the basic of OOP . It is the first function which will be called whenever a new object is created even it is called before the component is mounted. One thing should be noted that before any lines of statement ,you should call super(props) in order to use this.props.It will call the constructor of parent in order to avail “props” to our constructor.

This is also the only place where you are expected to change/set the state by directly overwriting the this.state fields. In all other instances remember to use this.setState.

componentWillMount(componentWillMount())

It is depricated. It is not that much different from constructor. It is invoked just before mounting occurs. It is called before render(), therefore calling setState() synchronously in this method will not trigger an extra rendering. But It is recommended to use constructor for the same.

render(render())

Among all the React developers , render() is most famous.  We create Elements (generally via JSX) and return them. We access the Component via this.props and this.state and these values tells about how content should be generated. Any changes we made  during  componentWillMount() are fully applied for this.state.

render() must not allow to modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in other lifecycle methods.

componentDidMount(componentDidMount())

componentDidMount() is invoked just after the mounting of a component. Statements that requires the DOM i.e which need the UI to be rendered should be kept here. Don’t use setState() in this method, as it will trigger an extra rendering . Though the user will not see the extra rendering but it will cause the performance issue.

componentWillReceiveProps(componentWillReceiveProps(nextProps))

It is depricated. componentWillReceiveProps() is invoked before a component receives new props. In this method you can compare the previous props with the newer one and based on that you can change the state and other updates

Calling this.setState() doesn’t trigger componentWillReceiveProps().

shouldComponentUpdate(shouldComponentUpdate(nextProps, nextState))

This can be used to let  React know if a component’s output is affected by the current change in state or props. Talking about the default behavious of this fuction, it will re-render on every state change.

This method is not called for the initial render. If this method returns false, then componentWillUpdate()render(), and componentDidUpdate() will not be invoked.

It is not recommend doing deep checks or using JSON.stringify() in shouldComponentUpdate(). It will degrade the performance badly.

componentWillUpdate(componentWillUpdate(nextProps, nextState))

This method is invoked just before rendering when new props or state are being received. This method is not called for the initial render. You can do the stuffs required before updation occurs

This method is only invoked if shouldComponentUpdate() will be invoked.

componentDidUpdate(componentDidUpdate(prevProps, prevState, snapshot))

This method is invoked just after updation occurs. This method is not called for the initial render. Statements that requires the DOM i.e which is needed after UI is updated should be kept here. It is the place where you can do the server call after comparing current and previous props.

componentWillUnmount(componentWillUnmount())

It is the method which is invoked immediately before a component is unmounted and destroyed. you can write the statements to cleanup any resource.

 

We can understand it with the help of example. Here we are setting the initial state inside of the constructor. The setDigit is used to update the state.

App.js

import React from 'react';
import Content from './Content';
class App extends React.Component {
   constructor(props) {
      super(props);
      
      this.state = {
         myDigit: 0
      }
      this.setDigit = this.setNewNumber.bind(this)
   };
   setNewNumber() {
      this.setState({myDigit: this.state.myDigit + 1})
   }
   render() {
      return (
         <div>
            <button onClick = {this.setDigit}>INCREMENT</button>
            <Content sentDigit = {this.state.data}></Content>
         </div>
      );
   }
}
export default App;

Content.js

import React from 'react'
class Content extends React.Component {
   componentWillMount() {
      console.log('Component WILL MOUNT!')
   }
   componentDidMount() {
      console.log('Component DID MOUNT!')
   }
   componentWillReceiveProps(newProps) {    
      console.log('Component WILL RECIEVE PROPS!')
   }
   shouldComponentUpdate(newProps, newState) {
      return true;
   }
   componentWillUpdate(nextProps, nextState) {
      console.log('Component WILL UPDATE!');
   }
   componentDidUpdate(prevProps, prevState) {
      console.log('Component DID UPDATE!')
   }
   componentWillUnmount() {
      console.log('Component WILL UNMOUNT!')
   }
   render() {
      return (
         <div>
            <h1>{this.props.sentDigit}</h1>
         </div>
      );
   }
}
export default Content

Main.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';

ReactDOM.render(<App/>, document.getElementById('app'));

setTimeout(() => {
   ReactDOM.unmountComponentAtNode(document.getElementById('app'));}, 5000);

After initial rendering, the screen will be-

and the console will be

Component WILL MOUNT!
Component DID MOUNT!

After clicking INCREMENT button, the updation will call other lifecycle methods.

Component WILL RECEIVE PROPS!
Component WILL UPDATE!
Component DID UPDATE!

And after 5 seconds, the component will unmount and the log will be

Component WILL UNMOUNT!

 

Leave a Reply