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
21
u/gaearon React core team Dec 07 '18 edited Dec 07 '18
Thanks for bringing this topic up! Probably worth blogging about at some point.
I replied on the video but I'll copy paste here.
This bug has nothing to do with either Hooks or concurrency.
The same exact bug would look like this in a class in sync mode:
To fix this bug, the best solution is simply to not have state that is calculated from another state. If
this.state.yis always calculated fromthis.state.x, removethis.state.ycompletely, and only trackthis.state.x. And calculate what you need when rendering instead. The same strategy applies to Hooks.If you must keep two states in sync for some reason, indeed, the solution at the end would work. This is similar to how you could solve it in a class:
Best to avoid but that works too.
With Hooks you could also
useReducerto centralize state update logic and avoid this pitfall.Why does this happen though?
setSomethingjust tells React to re-render the component later. It doesn't magically replace the setsomethingvariable in the current running function — that's not possible.1
u/swyx Dec 07 '18
a viewer replied with this codesandbox: https://codesandbox.io/s/ovw45xyp9z
basically use mutability to help patch the async-ness of the state update. it feels dirty but involves the least amount of refactoring
1
u/swyx Dec 07 '18
another follower chimed in with this:
4
u/leixiaotie Dec 07 '18
This is not specific related into react hooks, but Hooks makes this problem easier to reproduce. That's why in original class-based react, there are 2 setState operations:
In this version, it is clear (at least to me) that since setState is async, this.state.foo in that statement still using previous (latest) value, and not the result from rand(). It is fixed with the 2nd version, which is better in many ways for me:
This version, since setState is queued, and prevState will use latest updated state (in this case, rand()), it should update correctly.
Don't know how to do it in hooks, maybe useContext or something?
1
u/stalde Dec 07 '18
Ran into this myself as well. I think I've managed to minimize the re-producing example. Doesn't seem to be related to concurrency imo.
https://codesandbox.io/s/r73nk4nzqp
1
u/[deleted] Dec 07 '18 edited Dec 07 '18
A question kind of on the same topic: the setter function passed back from useState doesn't provide a callback, right? I ran into something where I wanted to wait for after the state updated and then do something in the callback. I guess with hooks though, it should just return from the component function and then whatever I wanted to originally do after setting state, do that on a re-render?
Also, thanks for putting this video together it was helpful.
1
u/eduleite Dec 07 '18
This is my take on the problem:
https://codesandbox.io/s/j4p289y969
For this situation, treating both states as a single state sounds to be the best aproach. The state variable is only updated when the hook is executed, and you don't have a way to peek into it in setState2 because both states are independent form each other. And since both state1 and state2 are linked, sounds more reasonable to deal with both in a single state variable.
2
u/[deleted] Dec 08 '18 edited Dec 08 '18
When I first was playing with hooks, I wanted to see how far I can go in terms of making a form library that was similar to formik w/ hooks.
Eventually I ran into a scenario that is similar to the mentioned gotcha. I wanted to expose to the user a
setFieldValuefunction. The setFieldValue function in formik sets a value for a certain form field. The developer can then choose whether validations can run after.The way that formik has implemented it though is using the 2nd argument to setState, which runs after the first setState (see https://github.com/jaredpalmer/formik/blob/master/src/Formik.tsx#L387).
In hooks...
https://github.com/facebook/react/commit/bf9fadfcf42847fa89f9a76c7d4dc2e2c17ee020#diff-932f37c41b864ce604eb14bb8e1481fdL249
the callback argument is removed and not supported. Instead it was suggested to use
useEffect, which some folks have mentioned.codesandbox I had: https://codesandbox.io/s/7j5pjw51pj
Scenario I am trying to implement:
Originally, I had something like:
which works. It logically makes sense - the validations that were being run was not on the current set of values of the form, but the future set of values of the form.
However, the assumption had an issue: what if the values that come in from
props.valuesis invalid to begin with? That's whereuseEffectsolves the problem.