Open In App

Explain new lifecycle methods in React v16.3

Last Updated : 23 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

React 16.3 introduced significant updates, deprecating and discouraging the usage of three lifecycle methods—`componentWillReceiveProps()`, `componentWillUpdate()`, and `componentWillMount()` by adding the “UNSAFE_” prefix due to potential misuse and issues in the code. The new Ref API and other changes were also introduced in this update.

React 16.3 has introduced two new lifecycle methods: 

Steps to Create the React Application And Installing Module:

Step 1: To create a react app, open your command prompt and start writing the following command:

npx create-react-app name-of-your-folder

Step 2: After following the above command, A folder will be created with ‘name-of-your-folder’ name then moved to this folder by the following command:

cd name-of-your-folder

Project Structure:

Screenshot-from-2023-11-10-14-57-33

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",
}

getDerivedStateFromProps():  This lifecycle hook is a static lifecycle hook. It is executed whenever the component receives updated props and it gives the chance to return an object which will become the new component state thereafter. It is used to bring component props and states into sync. This method is called before any updation of the component.

Syntax:

class ExampleHook extends React.Component {
static getDerivedStateFromProps(props, state) {
// statements...
}
}

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

Example: The `App` component in this React code defines a constructor, logs messages during initialization, sets a default state, and utilizes the `getDerivedStateFromProps` lifecycle method for handling state based on props, rendering a `Student` component with the name “Rahul.”

Javascript




import React, { Component } from "react";
import Student from "./Student";
 
export class App extends Component {
    constructor(props) {
        super(props);
        console.log("APP-Constructor Called");
        console.log(props.name);
        this.state = {
            roll: "101",
        };
    }
    static getDerivedStateFromProps(props, state) {
        console.log("App-Get deriving state from props");
        console.log(props, state);
        return null;
    }
    render() {
        return (
            <div>
                <Student name="Rahul" />
            </div>
        );
    }
}
 
export default App;


Output: 

getSnapshotBeforeUpdate(): This is executed right before the component does update which means right before your changes are committed to the DOM. This method is called which displays the previous value of the state. 

Syntax:

class ExampleHook extends React.Component {
getSnapshotBeforeUpdate(prevProps, prevState) {
// statements...
}
}

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

Example: The `App` component in this React code demonstrates the use of lifecycle methods, initializing state in the constructor, updating state after mounting, and displaying previous and current state values before and after updates.

Javascript




import React, { Component } from "react";
 
export class App extends Component {
    constructor(props) {
        super(props);
        console.log("APP-Constructor Called");
        console.log(props.name);
        this.state = {
            name: "first",
        };
    }
    componentDidMount() {
        setTimeout(() => {
            this.setState({ name: "last" });
        }, 3000);
    }
    getSnapshotBeforeUpdate(prevProps, prevState) {
        document.getElementById(`prev`).innerHTML = prevState.name;
 
        return prevState.name;
    }
    componentDidUpdate(prevProps, prevState, snapshot) {
        console.log(snapshot);
        document.getElementById(`current`).innerHTML = this.state.name;
    }
    render() {
        return (
            <div>
                <div id="prev">{this.state.name}</div>
                <div id="current">{this.state.name}</div>
            </div>
        );
    }
}
 
export default App;


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads