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
5
u/gaearon React core team Dec 07 '18
This is unnecessary. Why add extra work like running an effect when you already know the next value? Instead, the recommended solution is to either use one variable instead of two (since one can be calculated from the other one, it seems), or to calculate next value first and update them both using it together. Or, if you're ready to make the jump,
useReducerhelps avoid these pitfalls.