3 ms·
Here's how I'm pretty sure they work (although I haven't actually looked at the internals). Since your `<Tagname props>children</Tagname>` gets turned into `Rea
by Matheus28 4y ago
Here's how I'm pretty sure they work (although I haven't actually looked at the internals). Since your `<Tagname props>children</Tagname>` gets turned into `React.createElement(Tagname, props, children)`, this means your `Tagname` function isn't called directly. So before it calls that function, it sets up a "context" that the hooks will use during that function call (with a global variable pointing to that context so the hooks can find it). We could use an array with one element for each hook invocation. So each useState would use a different slot in that array, etc. This is also why the order and number of hooks must always be the same for a given function, since their identifier is their index in that array.
Additionally, this context would also have the context of children elements, so things can actually be persisted across function calls and React can know what needs to be mounted & unmounted.
Also note that because Tagname isn't called directly, it's also how React is able to do its diff and only actually call what is needed.
This is also why if you're generating a dynamic number of elements (ie outputting an array of elements), you should provide a `key` prop, so it can link up the elements to their corresponding past states each time the function runs.