React: prevState vs. Spread Operator or Both?

What’s the difference between these two setState commands? Don’t they do the same thing?

i’m trying to update a state object and need to keep all the elements I’m not updating, and only change one at a time dependinng on the program flow

this.setState(prevState => ({
    jasper: {                   // object that we want to update
        ...prevState.jasper,    // keep all other key-value pairs
        name: 'something'       // update the value of specific key
    }
}))
this.setState({
    jasper: {
          ...this.state.jasper,
          name: 'something'
    }
})

setState is asynchronous and can be batched by React, so it could be possible to have stale data in your second example. If you need to ensure that you have the correct state values, you need to use the callback form of setState like in your first example.

1 Like

Thank you. I read more on the prevState examples and realized it’s a variable in a callback, not a key word or specific function (right?). calling state inside of set state didn’t seem right to me.

Additionally, I’m not calculating anything based on previous state (like incrementing a counter for example), but I have several items in the state object that I DON"T want to change. So the call back example is still correct, right?

I’ve been coding react very recreationally for about 2 years but these thingn somehow don’t stick in my brain !

I read more on the prevState examples and realized it’s a variable in a callback, not a key word or specific function (right?).

That’s right!

I have several items in the state object that I DON"T want to change. So the call back example is still correct, right?

Right again!

You might investigate if there’s a way to flatten the properties you’re interested in so you would only be updating the ones that change when they change, but that may not be feasible depending on your requirements/implementation. When you’re updating objects like that, I’m not sure that React isn’t replacing them all anyway.

I’ve been coding react very recreationally for about 2 years but these thingn somehow don’t stick in my brain !

It’s been my day job for a bit longer than that and I still forget things like this. Thankfully, console warnings tell me when I screw this one up :laughing:

I created this particular object called “Behavior” so I can debug the behavior of the app more easily based on flags like “reviewMode”, “studyMode”, “unanswered”. these are all true/false and before, I had a hard time tracking them all simultaneously. In an object they are all grouped together…that’s the only reason they are not already flattened.

Thankns again!