Search code examples
javascriptreactjsreact-lifecycle

How to properly return updated state when using getDerivedStateFromProps lifecycle method?


For example we have such state:

state = { hasSomething: true, anotherKey: '', ... }

and we should update only 'hasSomething':

static getDerivedStateFromProps(nextProps) {
        if (nextProps.accessKey === 'admin') {
            return {
                hasSomething: false,
            };
        }
        return null;
    }

do we need to destruct the prevState when we return new state? for example like this:

static getDerivedStateFromProps(nextProps, prevState) {
    if (nextProps.accessKey === 'admin') {
        return {
            ...prevState,
            hasSomething: false,
        };
    }
    return null;
}

or we don't need it? i checked the console.log(this.state) and it returns the whole local state if im not make a prevState destructing.

i can't find this information in official react documentation :(

P.S. this logic just an example :)


Solution

  • The official documentation says It should return an object to update the state, or null to update nothing. (https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops). It is not cleared the state when you return only part of it, so it works like setState (https://reactjs.org/docs/react-component.html#setstate). The setState documentation says You may optionally pass an object as the first argument to setState() instead of a function. This performs a shallow merge of stateChange into the new state., so you don't need to destruct the previous state.