techStackGuru

React Lifecycle Methods


A React component's lifecycle consists of a series of methods that are invoked at various stages. The lifecycle of a component can be controlled and manipulated using these methods.

react-lifecycle-diagram

React component lifecycle in a nutshell:

Mounting Phase:

  • constructor()
  • static getDerivedStateFromProps()
  • render()
  • componentDidMount()
  • Updating Phase:

  • static getDerivedStateFromProps()
  • shouldComponentUpdate()
  • render()
  • componentDidUpdate()
  • Unmounting Phase

  • componentWillUnmount()
  • Furthermore, there are a few other lifecycle methods available, such as static getDerivedStateFromError() and componentDidCatch().

    The following example shows how React lifecycle methods can be applied to a class component:

    import React, { Component } from 'react';
    
    class MyComponent extends Component {
      constructor(props) {
        super(props);
        this.state = {
          count: 0,
        };
      }
    
      componentDidMount() {
        console.log('Component mounted');
      }
    
      componentDidUpdate(prevProps, prevState) {
        if (prevState.count !== this.state.count) {
          console.log('Count updated');
        }
      }
    
      componentWillUnmount() {
        console.log('Component will unmount');
      }
    
      incrementCount() {
        this.setState(prevState => ({
          count: prevState.count + 1,
        }));
      }
    
      render() {
        return (
          <div>
            <p>Count: {this.state.count}</p>
            <button onClick={() => this.incrementCount()}>Increment</button>
          </div>
        );
      }
    }
    
    export default MyComponent; 

    Using this example, we have a MyComponent class component that maintains a count. Here are the methods used in the lifecycle:

    constructor

    Constructors are called when components are first created. A 0 is set as the initial count when the state is initialized.

    componentDidMount

    As soon as a component is mounted (i.e., inserted into the DOM), this method is invoked. A console message is logged to indicate that we have mounted the component in this example.

    componentDidUpdate

    Whenever a component updates and re-renders, this method is called. In addition to the previous props and state, it receives the new props and state as arguments. Whenever there is a difference between the previous count and the current count, we log a message.

    componentWillUnmount

    When the component is unmounted and destroyed, this method is invoked. You can use it to perform any cleanup operations you need. This example logs a message to the console indicating that the components will be unmounted.