News for hackers. Stuff that matters.
Re:Introducing Hooks by Illniyar on Friday October 26, 2018 @07:56AM (#18308417)
The magic isn't what React.Component itself does, really it's the use of global variables (or close enough), because there is no other way in js to know inside useState what component called it.

The only way I can see this implemented is that when react calls your component function, it then keeps it a note of it in somekind of globally shared variable and then when useState is called it access that same shared variable to get the state.

It's also dependent on call order - that's a sure sign of magic work.

Re:Introducing Hooks by ascagnel_ on Friday October 26, 2018 @08:42AM (#18308649)
React has some knowledge of a given component through the use of `createElement` (or its JSX equivalents), so it's not even using global variables.

https://reactjs.org/docs/hooks-faq.html#how-does-react-assoc...

The "memory cells" the FAQ mentions sounds awfully like a map structure where React uses some internal identifier generated on first render to map any state handlers. The only "magic" bit is that it relies on the order of the `use` calls to be the same every time.

Re:Introducing Hooks by Illniyar on Friday October 26, 2018 @10:38AM (#18309578)
It is a globally shared variable.

Really either react notifies or registers the component to the module to exports useState, or more likely useState goes to some react internal api and retrieves the currently running component.

It's as much a global variable as the singleton pattern.