#Why setState doesn't actually update state

8 messages · Page 1 of 1 (latest)

last kettle
#

Guys, I met an interesting problem in Learn React for free> Meme generator > Boxes challenge part 5 for toggle function

When I update prevState inside setState and return prevState the real state is not updated (the whole component does not rerender as well). However console.log shows the correctly updated prevState before I return prevState and when I use the function (toggle) again it takes the updated prevState and also correctly update it

The problem is gone if I return a copy of [...prevState] instead of prevState. In that case the state and component are updated correctly

Why doesn't it work in the first case?

feral blade
#

I could be wrong about this, but I think that since squares is an array, prevSquares is just a reference to that value, rather than the value itself — and consequently, when you modify prevSquares, you're modifying squares/the state itself. So, you're essentially mutating the state in the process of trying to set the state — even though the whole point of setting the state is to avoid mutating it (state is supposed to be immutable) !

I can't explain exactly why it ends up behaving the way it does here, but the more general point is that attempting to mutate state leads to weird behavior, so you should avoid doing it.

Anyway, I'll post something in one of the pro student channels to see if someone more experienced/knowledgable than me can weigh in.

brazen sapphire
# feral blade I could be wrong about this, but I think that since squares is an array, prevSqu...

You are correct @feral blade.
@last kettle If you don’t have a primitive value in a dispatch/setter you will get back the reference of the value, hence any mutation on the value will not change the actual value of the state, since the reference did not change.
Because of that, react doesn’t know of any actual change happened, since you return the same reference as before.
That’s why it is recommended to be familiar with es6 array methods, most of the array methods return a brand new array, so the reference will be different and state change can be properly detected. You can always use spread operator for objects and arrays as well to make a shallow copy of your data then mutate it afterwards, but I would recommend trying to use immutable approach.

#

I am from mobile so if something wasn’t clear let me know and I could explain it better later today.

feral blade
brazen sapphire
last kettle
#

@brazen sapphire @feral blade Guys, thank you so much! You cleared that up for me

brazen sapphire
#

We are always happy to help 🙂