Hacker News new | ask | show | jobs
by alanning 1700 days 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)
2 comments

Ah, the code example doesn't work. User ptx clarified in a separate comment that the author meant it as just psuedo-code; it's value will be different in the next function invocation: https://news.ycombinator.com/item?id=28969530
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