Open In App

Explain the React component lifecycle techniques in detail

React components are the reusable and independent bits of code that help build the user interface of a webpage. Each of these components has various lifecycle methods which are invoked at different stages of their lifecycle. There are 4 stages in the lifecycle of a react component.

React Component Lifecycle Techniques:

Initialization:

It is the first stage of a React Component’s lifecycle. The component is defined with the default props and its initial state in the constructor of the component. This phase occurs only once in the lifecycle before the creation of the component or any props from the parent is passed into it and consists of the following methods which are called in the same order.



Note: The following methods only work with the “create-react-class” module and would throw errors with ES6 classes.




var createReactClass = require('create-react-class');
var Meeting = createReactClass({
    getDefaultProps: function () {
        return {
            dialogue: 'Good Afternoon!'
        };
    },
});




var createReactClass = require('create-react-class');
var Greeting = createReactClass({
    getInitialState: function () {
        return { message: 'Hello!' };
    },
 
    handleClick: function () {
        alert(this.state.message);
    },
 
    render: function () {
        return (
            <button onClick={this.handleClick}>
                Say hello
            </button>
        );
    }
});

2. Mounting: It is the second stage of a React components’ lifecycle. In this stage, the component is mounted on the DOM and rendered for the first time on the webpage after the component has been initialized. It consists of the following methods which are called in the same order.



  1. React elements
  2. Arrays and fragments
  3. Portals
  4. String and numbers
  5. Booleans or null

Note: The method below is considered legacy and should be avoided in new code.

componentWillMount() { 
this.setState({ name: "Component will mount." });
}

3. Updating: It is the third stage of a React components’ lifecycle. In this stage, the state and props are updated following various user events like clicking on a button, pressing a certain key, etc. We can communicate with the hierarchy of the components and handle user interaction on the webpage. It allows us to ensure that the component is presenting its latest version as required, therefore, it is called multiple times. It consists of the following methods.

Note: The methods below are considered legacy and should be avoided in new code.

componentWillUpdate() { 
this.setState({ name: "Component will update." });
}

componentWillReceiveProps(nextProps) {
console.log('componentWillReceiveProps', nextProps);
this.setState(nextProps);
}

4. Unmounting: It is the fourth and final stage of the React components’ lifecycle. It is invoked when the components’ instance is unmounted and destroyed from the DOM. This stage only contains a single method.

Steps to create the Project:

Step 1: Create the react application:

npx create-react-app myapp

Step 2: Change the directory:

cd myapp

Project Structure:

Project Structure

The updated dependencies in package.json file will look like:

  "dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Let’s take a look at the code snippet below which displays a demonstration of most of the lifecycle methods we have read about so far.




import React from 'react';
import ReactDOM from 'react-dom';
 
class LifecycleStages extends React.Component {
 
    // Initialization stage
    constructor(props) {
        super(props);
        this.state = { name: "GeeksForGeeks" };
    }
 
    // Mounting stage
    static getDerivedStateFromProps(props, state) {
        console.log("getDerivedStateFromProps()");
    }
 
    changeState() {
        this.setState({ name: "Geek!" });
    }
 
    render() {
        return (
            <div>
                <h2>React components' lifecycle methods</h2>
 
                <p>Hello {this.state.name}</p>
 
                <button onClick={this.changeState.bind(this)}>Don't Click.</button>
            </div>
        );
    }
 
    componentDidMount() {
        console.log("componentDidMount()");
    }
 
    componentWillMount() {
        console.log("componentDidMount()");
    }
 
    // Updating stage
    shouldComponentUpdate(newProps, newState) {
        console.log("shouldComponentUpdate()");
        return true;
    }
 
    getSnapshotBeforeUpdate(prevProps, prevState) {
        console.log("getSnapshotBeforeUpdate()");
    }
 
    componentDidUpdate(prevProps, prevState) {
        console.log("componentDidUpdate()");
    }
 
    // Unmounting stage
    componentWillUnmount() {
        console.log("Component will unmount.");
    }
}
 
export default LifecycleStages;

Step to run the application: Open the terminal and type the following command. 

npm start

Output:


Article Tags :