Sunday, September 22, 2024
Google search engine
HomeLanguagesReact.js static getDerivedStateFromProps()

React.js static getDerivedStateFromProps()

The getDerivedStateFromProps() method is used when the state of a component depends on changes of props.

getDerivedStateFromProps(props, state) is a static method that is called just before render() method in both mounting and updating phase in React. It takes updated props and the current state as arguments.

We have to return an object to update state or null to indicate that nothing has changed.

Creating React Application:

  • Step 1: Create a React application using the following command:

    npx create-react-app foldername
  • Step 2: After creating your project folder i.e. foldername, move to it using the following command:

    cd foldername

Project Structure: It will look like the following.

App.js




import React from 'react';
import ReactDOM from 'react-dom';
  
class App extends React.Component {
  
  render() {
  
    return (
      <div>
      <Child name = "sachin"></Child>
      </div>
    )
  }
}
  
class Child extends React.Component{
    constructor(props){
        super(props);
        this.state = {
        name: "kapil"
        };
    }
    static getDerivedStateFromProps(props, state) {
        if(props.name !== state.name){
            //Change in props
            return{
                name: props.name
            };
        }
        return null; // No change to state
    }
    /* if props changes then after getDerivedStateFromProps
       method, state will look something like 
  
    {
        name: props.name
    }
    */
    render(){
       return (
        <div> My name is {this.state.name }</div>
       )
    }
}
                      
export default App;


If props changes, then the state will also change accordingly else, getDerivedStateFromProps will return null that indicates no change in state. In the above example props have a property called name but the state has that property with a different value. so the state will change according to the value of props property.

Output:

Reference: https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

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