r/reactjs • • 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

9 Upvotes

26 comments sorted by

View all comments

Show parent comment

3

u/gaearon React core team Dec 07 '18

Depends on what you mean by a "closure thing" :-)

state is just a variable. setState doesn't mutate it immediately (and of course it can't reassign it). setState tells React to re-render the component, and during that render state will be set to the new value.

const [foo, setFoo] = useState(0)

function handleClick() {
  setFoo(42)
  // you can't expect this to somehow immediately change `foo`
  // we even declared it with const :-)
  console.log(foo); // 0
  // but on next render, `foo` will be 42
}