top | item 28969605

(no title)

alanning | 4 years ago

Yes, my feelings exactly. :-)

Any idea how useState accomplishes the mutation of the n-1 element mechanically? Seems to violate the by-value and by-reference rules in my mental model of how javascript works.

I was originally guessing it was a syntax trick of destructuring where it’s actually calling some kind of property accessor behind the scenes even if you don’t type the parentheses. But the article says this also works so now I don’t know…

  const loadingTuple = React.useState(true)
  const loading = loadingTuple[0]
  const setLoading = loadingTuple[1]

  loading // true
  setLoading(false)
  loading // false
(Edited to fix code formatting)

discuss

order

imtringued|4 years ago

setLoading just pushes an element into a queue. Calling useState will create the queue and fill it with true as initial state during the first call and then run a reducer on the entire queue to calculate the latest state. Simply calling setLoading does not modify loading. When you push an update to a queue react will rerender the component and thereby call useState again which runs the reducer which returns the latest state.

https://news.ycombinator.com/item?id=28972892