getDerivedStateFromProps not updating state?

84 Views Asked by At

I have this scenario:

static getDerivedStateFromProps(nextProps, prevState) {
        if(...) {
            console.log("A")
            return {
                a: true
            }
        }
        console.log("B")
        return {
            a: false
        }
    }

    shouldComponentUpdate() {
        const { a } = this.state
        console.log(a)
        return a
    }

Now running this I get

A
false

So what am I missing here? Shouldn't getDerivedStateFromProps update the state?

1

There are 1 best solutions below

0
On

Okay, I realized the error quite quickly now. To use the updated state in shouldComponentUpdate you have to use the parameters shouldComponentUpdate(nextProps, nextState) and not this.state.