Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React - Are all state properties required to be returned by getDerivedStateFromProps?

When using the getDerivedStateFromProps lifecycle method in a React component, does the state that is returned fully overwrite the components' existing state, or does it simply update the specific state properties that are returned? For example,

class foo extends Component {
  constructor() {
    this.state = {
      one: true,
      two: false,
    }
  }

  getDerivedStateFromProps(props, state) {
    ...
    return {
      one: false,
    }
  }

  ...  
}

Will the state be:

{ one: false }

or

{
  one: false,
  two: false,
}

?

like image 846
JoeTidee Avatar asked Nov 08 '25 09:11

JoeTidee


1 Answers

It will update the piece of state that is present in the object you return and leave the other state untouched, as it is stated in the documentation:

getDerivedStateFromProps is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.

Example

class App extends React.Component {
  state = { one: 1 };

  static getDerivedStateFromProps() {
    return { two: 2 };
  }

  render() {
    return <div>{JSON.stringify(this.state)}</div>;
  }
}

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>

<div id="root"></div>
like image 197
Tholle Avatar answered Nov 09 '25 21:11

Tholle