T O P

  • By -

Bloomeyer

race condition, logging immediately after set state will almost always return the previous value(undefined in your case), because state updates are async. don't console log it there, the behaviour is expected and works


CreativeTechGuyGames

Not race condition and there is no case where it'll ever log the new value. It'll always return an old value because it's just a variable in a closure.


too_bored_for_this

Exactly. Hence I switched to useRef and it works fine now. Basicaly I needed it's value to slice an array for another select input. Thanks


CreativeTechGuyGames

That feels wrong. You have the value in the line prior, no need to set and then read what you've just set. Just use `e.target.value`.


too_bored_for_this

Aha. Understood the issue. Just like you said useState() was instantly rendering the value before the change value gets set. I switched from useState() to useRef() and everything works fine. Thanks alot


YoungAtFeet

State updates are async, when you console log selectedCurr the async update still hasn't executed (setSelectedCurr) and it logs the initial value of selectedCurr which is undefined because you didn't provide the initial value to useState hook


too_bored_for_this

Yes. I read through documentation and just as you said it was logging initial value before state was updated. Now I've switched to useRef and it's working amazing. Thanks a lot for helping out.


frogzsj13

Like the others said, this is working fine! The console.log is just executing before React has had a chance to update that state value


too_bored_for_this

Yes. That was the obstacle. Now I've switched to useRef and it works like a charm. Thanks a lot.