r/reactjs • u/swyx • Dec 07 '18
React Team Comments React Hooks setState Gotcha
ran into a React Hooks setState Gotcha today:
https://www.youtube.com/watch?v=8NDSr9Vz6H4
Depending on how you view it, this is either a closure or a concurrency issue. Easy to run into if you are doing consecutive setStates. Because useState's setter doesnt offer a generic callback (it does offer a specific callback), you may need to "lift common variables up".
EDIT: NOT a concurrency issue - see Dan's reply below. as always its slightly scary to post up my failures for pple to see but i hope people understand i am just sharing my own pain points that i am bumping into. defintely not react's fault.
https://codesandbox.io/s/67zo2knpn
happy to take suggestions on how to improve
View all comments
Show parent comment
1
u/stalde Dec 07 '18
I can't tell myself either, lol. Funnily enough, if you click the button again, then it updates to the updated value (bar). This can be seen in your example as well. I assume it's a closure thing, but shouldn't the function be re-created with the new updated value?
Tried asking Dan as well, but no response.