Home >> Interviews Q & A >> React Component Lifecycle Methods with Examples

React Component Lifecycle Methods with Examples

React Component Lifecycle: Let's Learn and Understand React Component LifeCycle methods with Examples. In React.js Component Lifecycle Methods comes under three phases - Mounting, Updating, Unmounting etc.
In React, Lifecycle methods are various methods which are invoked at different phases of the lifecycle of a component.
React Component Lifecycle Phases (Updated as Version 16.8):

In React.js component goes through the following phases:

  1. Mounting Phase:

    In Mounting Phase, following methods are called during the Initial Rendering of DOM in the following order.

    • constructor()
    • static getDerivedStateFromProps()
    • render()
    • componentDidMount()

    Note: Following methods are considered legacy and you should avoid this:

    • UNSAFE_componentWillMount()
  2. Updating Phase:

    In this Phase, An update can be caused by changes to props or state of the component. these methods are called in the following order when a component is being re-rendered.

    Updation is the process that occurs when a component's state or properties (props) get updated.
    • static getDerivedStateFromProps()
    • shouldComponentUpdate()
    • render()
    • getSnapshotBeforeUpdate()
    • componentDidUpdate()

    Note: Following methods are considered legacy and you should avoid these:

    • UNSAFE_componentWillUpdate()
    • UNSAFE_componentWillReceiveProps()
  3. Unmounting Phase:

    This method is called when a component is being removed from the DOM:

    Unmounting is the process that occurs when a component is unmounted from the DOM.
    • componentWillUnmount()
You may also like - React.js Interview Questions Answers

Most Commonly Used Lifecycle Methods:
  • render()
  • constructor()
  • componentDidMount()
  • componentDidUpdate()
  • componentWillUnmount()
Rarely Used Lifecycle Methods:
  • shouldComponentUpdate()
  • static getDerivedStateFromProps()
  • getSnapshotBeforeUpdate()
You may also like - JavaScript Interview Questions Answers
Let's discuss in details: React Component Lifecycle Methods
  1. constructor():
    constructor() method gets called only once during Initial Rendering.

    In React.js, constructor are used for:

    • Initializing values of - props and state.
    • Binding event handler methods to an instance.
    import React, { Component } from "react";
    class myComponent extends Component {
      constructor(props) {
        super(props);
        // Don't call this.setState() here!
        this.state = { counter: 0 };
        this.handleClick = this.handleClick.bind(this);
      }
    }
    

    Note:

    1. Constructor is called only once in the complete lifecycle of a component.
    2. Constructor is the only place where you should assign this.state directly. In Other React's Lifecycle methods, you should use this.setState().
    3. If you are implementing the constructor, then you should call super(props) before any other statement. if you will not call super(props), this.props will be undefined in the component, which can lead to bugs.
  2. static getDerivedStateFromProps(nextProps, prevState)
    import React, { Component } from "react";
    class Example extends Component {
      static getDerivedStateFromProps(nextProps, prevState) {
        if (nextProps.myValue !== prevState.myValue) {
          return { myState: nextProps.myValue };
        } else {
          return null;
        }
      }
    
      componentDidUpdate(prevProps, prevState) {
        if (prevProps.myValue !== this.props.myValue) {
          this.setState({ myState: myValue });
        }
      }
    }
    

    getDerivedStateFromProps is newly added lifecycle method, is invoked after a component is instantiated as well as when it receives new props.

    It can return an object to update state, or null to indicate that the new props do not require any state update

    Together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillReceiveProps.

    getDerivedStateFromProps is a static method, therefore neither you access this inside this method nor you can access any other class method.

    Note: Following methods are considered legacy and you should avoid these:

    • UNSAFE_componentWillReceiveProps.
  3. render():
    render() is the most widely used react lifecycle method.
    • render() function returns only one react element (DOM component). If you wants to return multiple HTML elements it must be grouped inside one HTML tag.
    • render() method called by default because it needs to display the HTML markup or we can say JSX syntax.
    import React, { Component } from "react";
    class App extends Component {
      render() {
        return (
          

    Welcome to React component lifecycle methods!

    ); } } export default App;
    Q:- We can not define setState() inside render() method why?

    The application will be crash!

    Reason:- setState() function changes the state of the application and causing a change in the state called the render() function again (Re-Rendering). Therefore if you will use setState() function inside the render() method then component will be re-rendered and it will go in infinite loop and application will be crash!.

  4. componentDidMount():
    It is called immediately after the component did mounted in the DOM.
    import React, { Component } from "react";
    class myComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          name: "Full Stack Tutorials",
          website: "https://www.fullstacktutorials.com"
        };
      }
      getMyData() {
        this.setState({
          datalist: {
            name: "ReactJs Lifecycle Methods",
            website: "https://reactjs.org"
          }
        });
      }
      componentDidMount() {
        this.getMyData();
      }
      render() {
        return (
          

    Website Name: {this.state.datalist.name}

    Website Url: {this.state.datalist.website}

    ); } } export default myComponent;

    You may call setState() immediately in componentDidMount()

    Q:- Why is it recommended to do Ajax in componentDidMount?

    According to official React docs, the recommended place to do Ajax requests is in componentDidMount

  5. shouldComponentUpdate():

    it should return true or false value. This will determine if the component will be updated or not. This is set to true by default. If you are sure that the component doesn't need to render after state or props are updated, you can return false value.

  6. getSnapshotBeforeUpdate(prevProps, prevState)
    class Example extends Component {
      getSnapshotBeforeUpdate(prevProps, prevState) {
        // ...
      }
    }
    

    The new getSnapshotBeforeUpdate lifecycle is called right before mutations are made (e.g. before the DOM is updated). The return value for this lifecycle will be passed as the third parameter to componentDidUpdate. (This lifecycle isn’t often needed, but can be useful in cases like manually preserving scroll position during rerenders.)

    Together with componentDidUpdate, this new lifecycle should cover all use cases for the legacy componentWillUpdate.

  7. componentDidUpdate():
    componentDidUpdate() is invoked immediately after updating occurs.
    componentDidUpdate(prevProps, prevState, snapshot)
    
    componentDidUpdate(prevProps) {
    // Typical usage (don't forget to compare props):
     if (this.props.userID !== prevProps.userID) {
      this.fetchData(this.props.userID);
     }
    }
    

    You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop

    Note:

    • If your component implements the getSnapshotBeforeUpdate() lifecycle (which is rare), the value it returns will be passed as a third "snapshot" parameter to componentDidUpdate(). Otherwise this parameter will be undefined.
    • componentDidUpdate() will not be invoked if shouldComponentUpdate() returns false.
  8. componentWillUnmount():
    This method is called when a component is being removed from the DOM

    You should not call setState() in componentWillUnmount() because the component will never be re-rendered.

Full Stack Tutorials

Author @FullStackTutorials | View all Articles