setState should not directly change state. Never mutate state. Every time you do that, Dan Abramov kills a puppy. The callback function in setState should return an object that is what you want the knew state to be.
Correct. Why? Because. Or more accurately because that is how Redux was designed to work. Certain features of Redux will not work if you mutate state. Never, never do that. Always return the new state.
Yes, they both work, they both do the same thing. The difference is that the first one wraps it in an unnecessary extra function. I will almost always prefer the second one.
I’ve seen a few cases where the second won’t work, like if the function is from some library and it has optional other parameters, and the callback is getting sent other parameters so you need that extra layer to control what is getting passed. And of course if you need to pass in external parameters. But in general, the second option is cleaner.
I added [spoiler][/spoiler] tags since that is a working answer.
Yes, that works. You gave setState a new object. That is the right way to do it.
That is the old, “object” form of setState. Before you were trying the newer “functional” form of setState. The object form works in this case since the new state is not based on the old state, but you should learn the functional kind too. The difference is that instead of passing setState an object, you pass it a function that returns an object.
I’ve seen a few cases where the second won’t work, like if the function is from some library and it has optional other parameters, and the callback is getting sent other parameters so you need that extra layer to control what is getting passed..