Friday, November 29, 2024
Google search engine
HomeLanguagesExplain new lifecycle methods in React v16.3

Explain new lifecycle methods in React v16.3

React 16.3 has introduced some major updates like the new Ref API, lifecycle hooks changes, and much more. Right now, we will be focusing on the new lifecycle methods which are introduced by React 16.3. With React 16.3, The usage of three lifecycle methods i.e. (componentswillReceiveProps(), componentWillUpdate(), and componentWillMount()) are discouraged. These lifecycle methods were often misused (like in-state updates). So, these lifecycles are deprecating unsafe lifecycles in which they add the “UNSAFE_” prefix to these lifecycles. Unsafe means these lifecycles might give some issues in the code. 

React 16.3 has introduced two new lifecycle methods: 

  1. getDerivedStateFromProps()
  2. getSnapshotBeforeUpdate()

Creating a React Application:

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: The project structure will look like:

The structure of your react folder

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:

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: 

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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments