REACT COMPONENT LIFE-CYCLE

Kiruthika M

 React Component Life-Cycle

       In ReactJS, each component undergoes a series of lifecycle methods during its creation process. These lifecycle methods, which are not overly complex, are invoked at different stages of the component's life. The component's lifecycle is divided into four phases: 

       1. Initial Phase

       2. Mounting Phase

       3. Updating Phase

       4. Unmounting Phase

       Each phase includes specific lifecycle methods that are unique to that phase. Let's go through each of these phases individually.

1.Initial Phase

       This is the initial phase in the lifecycle of a ReactJS component, where the component begins its journey toward being rendered in the DOM. During this phase, the component holds its default props and initial state, which are typically set in the constructor. The initial phase occurs only once and includes the following methods.

getDefaultProps()

        It is used to define the default value of `this.props` and is invoked before the component is created or any props are passed from the parent.

getInitialState()

        It is used to set the default value of `this.state` and is invoked before the component is created.

2.Mounting Phase

        In this phase, the component instance is created and added to the DOM. It includes the following methods.

componentWillMount()

       This is invoked right before a component is rendered into the DOM. If you call `setState()` within this method, the component will not re-render.

componentDidMount()

       This is invoked immediately after a component is rendered and inserted into the DOM, allowing you to perform any DOM querying operations.

render()

       This method is defined in every component and is responsible for returning a single root HTML element. If you don't want to render anything, you can return `null` or `false`.

3.Updating Phase

       This is the next phase in the lifecycle of a React component, where new props are received and the state is updated. It also handles user interactions and facilitates communication within the component hierarchy. The primary goal of this phase is to ensure the component displays its most up-to-date version. Unlike the Birth or Death phases, this phase repeats continuously. It includes the following methods.

componentWillReceiveProps()

       It is invoked when a component receives new props. To update the state in response to prop changes, you should compare `this.props` with `nextProps` and use the `this.setState()` method to perform the state transition.

shouldComponentUpdate()

      It is invoked when a component determines whether any changes or updates are needed in the DOM. This method allows you to control the component's behavior when updating itself. If it returns `true`, the component will update; otherwise, it will skip the update.

componentWillUpdate()

     It is invoked just before the component is updated. In this method, you cannot change the component's state by calling `this.setState()`. It will not be called if `shouldComponentUpdate()` returns `false`.

render()

    It is invoked to examine `this.props` and `this.state` and return one of the following types: React elements, arrays and fragments, booleans or null, strings, or numbers. If `shouldComponentUpdate()` returns `false`, the code inside `render()` will be called again to ensure the component renders correctly.

componentDidUpdate()

    It is invoked immediately after the component has been updated. You can place any code inside this method that you want to execute after the update. This method is not called during the initial render.

4.Unmounting Phase

    It is the final phase of the React component lifecycle, called when a component instance is destroyed and removed from the DOM. This phase includes only one method, as described below.

componentWillUnmount()

    This method is invoked right before a component is destroyed and permanently unmounted. It handles any necessary cleanup tasks, such as invalidating timers, removing event listeners, canceling network requests, or cleaning up DOM elements. Once a component instance is unmounted, it cannot be mounted again.

Example

import React, { Component } from 'react';

class CounterApp extends React.Component {

   constructor(props) {

      super(props);

      this.state = { count: 0 };

      this.incrementCount = this.incrementCount.bind(this);

      this.decrementCount = this.decrementCount.bind(this);

   }

      render() {

      return (

         <div>

            <h1>ReactJS Component Lifecycle Example</h1>

            <h3>Current Count: {this.state.count}</h3>

            <button onClick={this.incrementCount}>Increment</button>

            <button onClick={this.decrementCount}>Decrement</button>

         </div>

      );

   }

    componentWillMount() {

      console.log('Component Will MOUNT!');

   }

    componentDidMount() {

      console.log('Component Did MOUNT!');

   }

   incrementCount() {

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

   }

  decrementCount() {

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

   }

   componentWillReceiveProps(newProps) {

      console.log('Component Will RECEIVE Props!');

   }

   shouldComponentUpdate(newProps, newState) {

      console.log('Should Component UPDATE?', newState.count);

      return true;

   }

  componentWillUpdate(nextProps, nextState) {

      console.log('Component Will UPDATE!');

   }

  componentDidUpdate(prevProps, prevState) {

      console.log('Component Did UPDATE!');

   }

 componentWillUnmount() {

      console.log('Component Will UNMOUNT!');

   }

}

export default CounterApp;

Output:


When you click the "Click Here" button, the result gets updated and is displayed on the screen below.




Our website uses cookies to enhance your experience. Learn More
Accept !

GocourseAI

close
send