In the real world, everything follows a lifecycle. For example, a human goes through various phases from birth to death, including childhood, adolescence, adulthood, and old age. During these phases, they behave differently. Similarly, in React, components go through a lifecycle(React Component Life Cycle) consisting of different phases. Each phase includes a set of lifecycle methods that trigger at specific points in the component’s lifecycle. These methods enable you to manage the component’s behavior and execute specific actions at various stages of its lifecycle.
 

A component’s lifecycle has three main phases: 

  • Mounting Phase:
    – The Mounting Phase starts when a component first creates and inserts itself into the DOM.
  • Updating Phase:
    – The Updating Phase takes place when a component’s state or props undergo changes.
  • Unmounting Phase:
    – The Unmounting Phase happens when a component gets removed from the DOM.

Component Mounting

The mounting phase is the period when a component is created and inserted into the DOM.

During this phase, React invokes several lifecycle methods, allowing the developer to configure the component, establish any required state or event listeners, and complete other initialization tasks.

React features four built-in methods that are called, in the following sequence, during the mounting of a component:

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

NOTE : – The render() method is mandatory and must always be called, while the others are optional. You can define them as needed and then call them.

Remember that we cannot change the order of the methods.

The React Constructor is a method that the system automatically calls when an object is created from a class.

Constructors serve two primary purposes:
  • To initialize the local state of the component by assigning an object to `this.state`

  • To bind event handlers that occur in the component.

    React calls the constructor method every time a component is created.

				
					class Component1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = {val: 10};
  }
  render() {
    return (
      <h1>My The value is {this.state.val}</h1>
    );
  }
}

ReactDOM.render(<Component1 />, document.getElementById('root'));
				
			

In this example, the `constructor()` method sets the initial state of the component as an object with a `val` property set to `10`, and the `render()` method renders an `<h1>` element with the value of `val` set to `10`.

The static `getDerivedStateFromProps()` lifecycle method:

`getDerivedStateFromProps()` is a lifecycle method invoked during the mounting and updating phase of a component.

During the mounting phase, `getDerivedStateFromProps()` gets called after the constructor but before `render()`. This method is executed during each render cycle and offers the opportunity to update the component’s state based on changes in props before the initial rendering.

This method enables you to adjust the state value using any props value and is particularly valuable for handling changes in props over time.

The methodย static getDerivedStateFromPropsย accepts two arguments:ย propsย andย state, and returns an object, orย nullย if no change is needed.ย 

The signature of getDerivedStateFromProps ()

static getDerivedStateFromProps(props, state)

ย It has two parameters.

  1. propsย  : The updated props for the component.
  2. ย state : The current state of the component.

It’s important to note that `getDerivedStateFromProps()` is a static method, meaning it lacks access to the `this` keyword and cannot interact with the component’s instance methods or properties.

				
					import React, { Component } from 'react'

export class Component1 extends Component {
    constructor(props) {
      super(props)
    
      this.state = {
          val:10
      }
    }

    static getDerivedStateFromProps(props, state) {
        return {val: props.newval };
      }

  render() {
    return (
      <div>
        <h1>The Value is ${this.state.val}</h1>
      </div>
    )
  }
}

export default Component1
				
			

In this example our component class has constructor,ย ย that sets the initial state of val to 10. and render() method renders <h1> element with string that include value ofย  state.val

The componentDidMount() lifecycle method

The componentDidMount() method is called once the component has been mounted into the DOM. It is typically used to for the following purpose-ย 

  • to set up any necessary event listeners or timers
  • perform any necessary API calls or data fetching
  • Perform initialization that require access to the browser’s DOM API.
				
					import React, { Component } from 'react'

export class Component1 extends Component {
    constructor(props) {
      super(props)
    
      this.state = {
          val:10
      }
    }

    componentDidMount() {
    setTimeout(() => {
      this.setState({val: 100})
    }, 1000)
  }
  

  render() {
    return (
      <div>
        <h1>The Value is ${this.state.val}</h1>
      </div>
    )
  }
}

export default Component1
				
			

In the example above, the constructor initializes the state object property `val` with `10`.

The component also contains the `componentDidMount()` lifecycle method, which React invokes after the component has been mounted, indicating it’s been inserted into the DOM. Within this method, a `setTimeout` function is employed to introduce a delay in executing a function. This function subsequently updates the `val` state property to `100` after a one-second delay.

The render() lifecycle method

The render() method generates the virtual DOM representation of the component based on its current props and state. React calls this method whenever the component requires re-rendering, which occurs when its props or state change or when a parent component undergoes a rerender.

				
					import React, { Component } from 'react';

class Comp1 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      val: 0
    };
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(prevState => ({
      val: prevState.val + 1
    }));
  }

  render() {
    return (
      <div>
        <p>Val: {this.state.val}</p>
        <button onClick={this.handleClick}>Increment</button>
      </div>
    );
  }
}

export default Comp1;
				
			

The render method shows the current value of ‘val‘ and a button. When you click the button, it invokes the handleClick method. This action initiates a state update, leading to a re-render, and subsequently displays the updated ‘val‘ value.

Component Updating Phase

The next phase in component life cycle is to Update Phase. This phase occurs when a component’s props or state changes, and the component needs to be updated in the DOM.

React has following built-in methods that gets called, in thisย  Updating Phase :

  1. ย shouldComponentUpdate()ย 
  2. componentWillUpdate()
  3. componentDidUpdate()
  4. getSnapshotBeforeUpdate()

The shouldComponentUpdate() lifecycle method

The shouldComponentUpdate() method gets invoked before a component undergoes an update. It receives two arguments: nextProps and nextState. This method yields a boolean value that dictates whether the component should update. When this method returns true, the component updates; conversely, when it returns false, the component remains unchanged.

Let’s attempt an example demonstrating how to use shouldComponentUpdate().

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

class Comp1 extends Component {
  constructor(props) {
    super(props);
    this.state = { message:"Hello"};
  }

  shouldComponentUpdate(nextProps, nextState) {
    // Only re render if the message state has changed
    return this.state.message !== nextState.message;
  }

  changeMessage = () => {
    this.setState({ message: 'Hi' });
  }

  render() {
    return (
      <div>
        <h1>My The Message is {this.state.message}</h1>
        <button type="button" onClick={this.changeMessage}>Change </button>
      </div>
    );
  }
}
export default Comp1
				
			

In the example above, we define a Comp1 component responsible for displaying a message and enabling the user to modify it by clicking a button. To optimize performance, we’ve implemented the shouldComponentUpdate() method to trigger a re-render of the component only when the message state undergoes a change.

The componentWillUpdate() lifecycle method

It gets invoked right before the commencement of a component’s update cycle. This method receives the next prop and state as arguments, providing you with the opportunity to execute any essential actions before the component updates.

Its primary purposes include tasks such as making API calls, updating the DOM, or preparing the component to receive new data.

componentWillUpdate() is often used in conjunction with componentDidUpdate() to handle component updates.

The componentDidUpdate lifecycle method

The componentDidUpdate() method in React is an invoked lifecycle method that occurs after a component has been updated and re-rendered. It serves a useful purpose for executing side effects or carrying out additional operations when the component’s props or state have undergone changes.

				
					import React, { Component } from 'react';

class ExampleComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }

  componentDidUpdate(prevProps, prevState) {
    if (prevState.count !== this.state.count) {
      console.log('Count has been updated:', this.state.count);
    }
  }

  handleClick() {
    this.setState(prevState => ({
      count: prevState.count + 1
    }));
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.handleClick()}>Increment</button>
      </div>
    );
  }
}

export default ExampleComponent;
				
			

In this example, we employ the componentDidUpdate() method to log a message to the console when the count state has been modified. It conducts a comparison between the previous state (prevState.count) and the current state (this.state.count) to determine if a change occurred.

Whenever the handleClick() method is invoked, it increments the count state, leading to a component re-render. After the re-render, componentDidUpdate() gets called and logs the updated count value to the console.

It’s crucial to incorporate a conditional check within componentDidUpdate() to prevent infinite loops.

The getSnapshotBeforeUpdate() lifecycle method:

The getSnapshotBeforeUpdate() method gets invoked just before the component’s UI undergoes an update. Its purpose is to enable the component to capture specific information about the current state of the UI, such as the scroll position before any changes occur. The value returned by this method serves as the third parameter passed to the componentDidUpdate() method.

Component Unmounting Phase

This marks the concluding phase of the component’s lifecycle, where the component is removed from the DOM, rendering it inaccessible.

Throughout this phase, React carries out a sequence of cleanup operations to guarantee the proper disposal of the component and its associated resources.

The componentWillUnmount() lifecycle method

componentWillUnmount(): React invokes this method just before removing the component from the DOM. It provides an opportunity to carry out essential cleanup tasks, such as canceling timers, removing event listeners, or clearing data structures established during the mounting phase.

Upon completion of componentWillUnmount(), the component is eliminated from the DOM, and both its state and props are disposed of.

In summary, React components follow a lifecycle consisting of three phases: Mounting, Updating, and Unmounting. Each phase includes methods called at various points in the component’s lifecycle.

For more in React Join YouTube channel:ย 

K2infocom…

Leave a Reply

Your email address will not be published. Required fields are marked *