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,
}
?
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:
getDerivedStateFromPropsis 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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With