Skip to main content

Best Way To Learn ReactJS Component Lifecycle Methods, Hooks With Examples For Beginners, React JS Developer

ReactJS Component Lifecycle Overview:

ReactJS Component Lifecycle methods are hooks which are the main part of react framework. ReactJS lifecycle divide mainly into three parts, Mounting, Updating, and Unmounting. In ReactJS, we'll use ES6 (EcmaScript) syntax. In this post we'll learn the importance of each and every lifecycle method, how and where can we use the lifecycle method in reactjs application.

React Component LifeCycle Initial Rendering :


ReactJs Component Lifecycle: initial rendering



In initial rendering, getDefaultProps function is executed, it's used to set the default props value in case props doesn't pass from the parent component. In ES6, we have defaultProps which the replacement of getDefaultProps function. Lets see both syntaxes but we'll follow ES6 syntax. Next method is getInitialState which is used to set the initial state value. We have the constructor to set initial state in ES6.

Mounting

  • Initialization
  • componentWillMount
  • render
  • componentDidMount

Updating

  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

Unmounting

  • componentWillUnMount

Mounting

Mounting is the first phase of react lifecycle execution, componentWillMount, render, and componentDidMount methods are involked automatically in first render.
Initialization:In this phase, we can set initial state or props, lets explain by example. There is an Input component and there is a property placeholder will get through props, in this case we can set the initial state or default props to placeholder.
getDefaultProps, and getInitialState in ES5 syntax:
var Input = React.createClass({
    // Set up initial props
  getDefaultProps: function() {
    return {
      placeholder: 'enter name' 
    };
  },
  // Set up initial state
  getInitialState: function() {
    return {
      placeholder: this.props.placeholder,
      value:''
    };
  },
  handleChange: function(event) {
    this.setState({
      value: event.target.value
    });
  },
  render: function() {
    return (
      <div>
        Enter Name:
        <input onChange={this.handleChange} 
        placeholder={this.state.placeholder}
        value={this.state.value} />
      </div>
    );
  }
});

Initial state or default props ES6
 class Input extends Component {
  constructor(props) {
    super(props);
    this.state = {
      placeholder: props.placeholder
    };
    //bind function 
    this.handleChange=this.handleChange.bind(this);
  }

   handleChange(event){
    this.setState({
      value: event.target.value
    });
  }  

  render() {
    return (
      <div>
        Enter Name:
        <input
          onChange={this.handleChange}
          placeholder={this.state.placeholder}
          value={this.state.value}
        />
      </div>
    );
  }
}

Input.defaultProps = {
  placeholder: "enter name"
};

Input.propTypes={
    placeholder:PropTypes.string
}

export default Input;

Here we have a reactjs Input component in which placeholder property have initial state and default props, in case Input component doesn't get the placeholder props from parent component, it will display defaultProps such as 'enter name'. You can also set the props types, here we have Proptypes of placeholder such as string. In constructor, you can have  the initial state.

componentWillMount

The componentwillmount method is executed before rendering, on both server and client side. This is a good place to call API.This will not cause additional re-render.

import React, { Component } from "react";
import PropTypes from 'prop-types';

class ComponentLifeCycle extends Component {
  constructor(props) {
    super(props);
    this.state={API_Data:[]}
  }

componentWillMount () {
  fetch('http://api_url').then((result) => { 
   // This will not cause additional re-render
    this.setState({ API_Data: result.data});
  })
}

  render() {
    return( 
    <div>
      React Redux Tutorials-https://www.reactreduxtutorials.com
    </div>;
    );
  }
}

export default ComponentLifeCycle;

Render: In initial render, It's executed after componentWillMount and before componentDidMount.This render function is executed every time whenever the state is changed.

componentDidMount

The componentDidMount is executed just after the first render only on client side and before render function.The componentDidMount method runs after the component output has been rendered to the DOM. This is good place to integrate other JavaScript framework such as setTimeout or setInterval. It can be used to DOM manipulation to adding or removing DOM elements such as adding event listener.


componentDidMount Example
import React, { Component } from "react";
class ComponentLifeCycle extends Component {
  constructor(props) {
    super(props);
    this.state={API_Data:[]}
  }

handleScroll(evt){
  console.log(evt);
}

componentDidMount(){
 fetch('API_URL').then((result) => {
    // This in the other hand will cause additional rerender,
    // since fetch is async and state is set after request completes.
    this.setState({ API_Data: result.data});
  })

  //add scroll event listener
   window.addEventListener('scroll', this.handleScroll);
}

  render() {
    return( 
    <div>
      React Redux Tutorials-https://www.reactreduxtutorials.com
    </div>;
    );
  }
}

export default ComponentLifeCycle;
Here, componentDidMount method is invoked and call the API and adding scroll event listener. In handleScroll function, evt is a synthetic event. We'll discuss later synthetic events in details. We can use it to update the state so we can trigger the other lifecycle methods.

Updating

An update can be caused by changes to props or state. These methods are called when a component is being re-rendered. There is the list of lifecycle hooks through those components will update.
  • componentWillReceiveProps
  • shouldComponentUpdate
  • componentWillUpdate
  • render
  • componentDidUpdate

componentWillReceiveProps

componentWillReceiveProps is executed as soon as props are updated before another render. This is a good place to track the props or state changes. In this function we should always have the condition to avoid extra re-render component and we can use shouldComponentUpdate to restrict extra re-render component.

componentWillReceiveProps Example
import React, { Component } from "react";

  class ComponentWillReceivePropsExample extends Component {
  constructor(props) {
    super(props);
    this.state = { accounts: props.accountsList };
  }

  componentWillReceiveProps(nextProps, nextState) {
    if (this.props.accountList !== nextProps.accountList) {
      this.setState({ account: accountList });
    }
  }

  render() {
    const { accounts } = this.state;
    return accounts.map(item => (
      <div>
        <div>{item.accountId}</div>
        <div>{item.accountType}</div>
      </div>
    ));
  }
 }

 export default ComponentWillReceivePropsExample;
Here, We have accountList props which are passed to the parent component. The componentwillreceiveprops method is executed whenever props are changed. There are two parameter nextState and nextProps, props have previous value and nextProps have current value and same for state and nextState. Here we are comparing previous and current props value, the state will change if props in updated.

shouldComponentUpdate

This method should return the boolean value true or false. This will determine if the component will be updated or not. By default, it will return true. You can return a false value if you make sure that the component doesn't need to render after state or props are updated. This is the good place to avoid re-render component.

shouldComponentUpdate Example
import React, { Component } from "react";

class ShouldComponentUpdateExample extends Component {
  constructor(props) {
    super(props);
    this.state = { accounts: props.accountsList };
  }

  componentWillReceiveProps(nextProps, nextState) {
    if (this.props.accountList !== nextProps.accountList) {
      this.setState({ account: accountList });
    }
  }

  shouldComponentUpdate(nextState) {
    if (this.state.account !== nextState.account) {
      return true;
    }
    return false;
  }

  render() {
    const { accounts } = this.state;
    return accounts.map(item => (
      <div>
        <div>{item.accountId}</div>
        <div>{item.accountType}</div>
      </div>
    ));
  }
 }

 export default ShouldComponentUpdateExample;
Here, shouldComponentUpdate is returned false if state and nextState value are same. A component will not be rendered or re-render if the shouldComponentUpdate method returns false. we'll not need to use shouldComponentUpdate in react js version 16, there is a way to use pure component, don't need to use the shouldComponentUpdate method. It handles internally. We'll discuss later Pure Component.

componentWillUpdate

componentWillUpdate() is executed just before rendering when new state or props are being received. This is a good place to perform preparation before an update occurs. This method is not called for initial render. We can not call this.setState and redux action. componentWillUpdate() will not be invoked if shouldComponentUpdate() returns false.
The componentWillUpdate provides you control to manipulate the component just before it receives new props or state. I would like to use it to do animations.Fade an element out of the view, before removing the dom

componentWillUpdate Example
import React, { Component } from "react";
import ReactDOM from 'react-dom';

class ComponentWillUpdateExample extends Component {
  constructor(props) {
    super(props);
  }

  componentWillUpdate(newProps, newState) {
    if (!newState.display) {
      ReactDOM.findDOMNode(this.refs.elem).css({ opacity: "1" });
    } else {
      ReactDOM.findDOMNode(this.refs.elem).css({ opacity: "0" });
    }
  }

  render() {
    return <div>React Redux Tutorials</div>;
  }
}

export default ComponentWillUpdateExample;

componentDidUpdate

componentDidUpdate() is called immediately after rendering. This method is not called for the initial render.This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). This is also good place to do animation. I want to set focus of input field in componentDidUpdate() method.
componentDidUpdate Example
import React, { Component } from "react";

class ComponentDidUpdateExample extends Component {
  constructor(props) {
    super(props);
  }

  componentDidUpdate(nextProps, nextState) {
    if (this.nameInput) {
      this.nameInput.focus();
    }
  }

  render() {
    return (
      <div>
        React Redux Tutorials: componentDidUpdate() example
        <input
          ref={input => {
            this.nameInput = input;
          }}
          placeholder="enter name"
        />
      </div>
    );
  }
}

export default ComponentDidUpdateExample;

Here's, after rendering component focus will set on input field. This is an good example which is used in live applications.

Unmounting

Unmounting method is called when a component is being removed from the DOM. In this method we can do the memory release, unregister events etc. There is an Unmounting method i.e. componentWillUnmount()
componentWillUnmount Example
import React, { Component } from "react";

class ComponentWillUnmountExample extends Component {
  constructor(props) {
    super(props);
  }

  handleScroll(evt) {
    console.log(evt);
  }

  componentDidUpdate(nextProps, nextState) {
    if (this.nameInput) {
      this.nameInput.focus();
    }
  }

  componentDidMount() {
    //add scroll event listener
    window.addEventListener("scroll", this.handleScroll);
  }

  componentWillUnmount() {
    //removed event listener
    window.removeEventListener("scroll", this.handleScroll); //
  }

  render() {
    return (
      <div>
        React Redux Tutorials: componentDidUpdate() example
        <input
          ref={input => {
            this.nameInput = input;
          }}
          placeholder="enter name"
        />
      </div>
    );
  }
}

export default ComponentWillUnmountExample;

Here's, componentDidMount method is registered scroll event listener and componentWillUnmount is removed scroll event listener.

Points to be noted

  • Always export component at the end,not in starting with class. This will impact when we will use Redux.
  •  //It's an bad approach
     export default class Input extends Component{}
     //It's a good approach
     class Input extends Component{}
    
    export default Input;
  • Don't repeat this.state and this.props every time, try to use state and props as a const variables and follow always best react code practice
  •  class Payment extends Component {
      //It's bad practice to repeat this.state and this.props
      render() {
        return (
          <div>
            <div>{this.state.name}</div>
            <div>{this.state.address}</div>
            <div>{this.props.country}</div>
            <div>{this.props.state}</div>
          </div>
        );
      }
      //It's good practice
      render() {
        const { name, address } = this.state;
        const { country, state } = this.props;
        return (
          <div>
            <div>{name}</div>
            <div>{address}</div>
            <div>{country}</div>
            <div>{state}</div>
          </div>
        );
      }
    }
    
  • Always use wrapper div inside render function, otherwise you'll get the error
  •  class Payment extends Component {  
      render() {
        //It'll create error, it's not having wrapper element div
        return (     
            <div>{this.state.name}</div>
            <div>{this.state.address}</div>
            <div>{this.props.country}</div>
            <div>{this.props.state}</div>     
        );
      }
      
      render() {
        const { name, address } = this.state;
        const { country, state } = this.props;
        //It'll not create error, it's having wrapper element div
        return (
          <div>
            <div>{name}</div>
            <div>{address}</div>
            <div>{country}</div>
            <div>{state}</div>
          </div>
        );
      }
    }
    
    This wrapper element problem has resolved in React JS version 16.2,there is an concept Fragment, Will discuss late.
  • If you are not having Pure Component, follow to practice shouldComponentUpdate method to avoid extra re-render component.
  • Follow practice to use componentWillReceiveProps() method to handle the props changes in component.

Conclusion

In this post, we learned, what is the importance of each and every component lifecycle methods and how and where we can use each of one. we understood all the lifecycle methods for example and learned to follow good react js code practice and understand react js. I'll cover all the component lifecycle methods in more details in coming react redux post.
Have a good day...

Comments

Popular posts from this blog

React Redux Tutorials: React Redux Data Flow and Redux Lifecycle Methods With Examples

React Redux Data Flow and Redux Lifecycle Methods Overview What is Redux and why do we need Redux Redux is an open source JavaScript library which is designed for maintaining application state. Redux JS is a powerful and popular library nowadays. The command to install Redux library npm install redux --save . Nowadays JavaScript single-page applications are very popular and powerful. As the requirements for single-page applications have become complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally generated data that has not yet been persisted to the server. Front-end state is also increasing in complexity, as we need to manage active routes, selected tab, spinners, pagination controls etc. That's why we need Redux. click here to learn React Redux Architecture, folder structure. Three Principles of Redux: Changes are made with pure functions You write pure reducers to specify

React Redux Application Structure, Architecture and React Folder Structure Best Practices

React Redux Application Structure, Architecture and  React Folder Structure Best Practices: There some questions comes our mind when we are going to create a new react redux application structure from scratch. What folder structure should be followed especially when we are implementing a large react redux application . How to connect react with redux  What should be the naming convention of folder and react js files. What are the best practices of react redux project structure. The structure might be different for each of us but I am sharing the standard react redux application structure which is followed by most of the UI developers in IT industry. High Level React Redux Application Architecture There are many folders and files in above application screen shot, let discuss one by one. The application name is REACTWEBAPP and folders are config, public, script, server, src, reducers, sagas, store and package.json. Config: react redux application configurations

ReactJS Routing And Single Page Application Tutorial

React Router: ReactJS Single Page Application Why do we need React Router Nowadays single page application is the most popular. For making single page application, we need to react router. Single page application is very powerful and provides performance features as well. What is React Router React router is a library, it provides routing feature through which we can redirect from one page to another page. Mainly there are two types of routing. 1. Browser Specific routing: In general or e-commerce web application have browser routing and it helps in search engine optimization. npm command to install routing package npm install react-router --save . --save is used to save the package entry in project specific package.json file. import React from 'react'; import ReactDOM from "react-dom"; import { Router, Route, Link, browserHistory, IndexRoute } from 'react-router'; import Home from './Home'; import About from './About'; import