A question I had for a long time was: how do React hooks work?

Specifically, how do they associate a functional component with state, without requiring a stable identifier?

There are many high quality answers online. For me, they either focus to deeply on React internals (Fibers, render cycle, ReactFiberHooks), or they are too high level (“it’s just arrays”, closures, call order).

Here is an answer for me1:

  1. A JSX tag is transformed into a function call, passing in the tag name as a string, properties as an object, and its children as expressions (recursively transformed as well).
  2. The children of a JSX element are transformed into positional function arguments2 that have a stable order. This is stable even if they are conditionally rendered, since the conditional expression occupies the argument slot. List expressions need keys because JSX transforms them into a single argument.
  3. Hooks use order within the JSX tree to index into which component state to load.
  4. Hooks within the same component are distinguished by call order in that component. This is possible because of the Rules of Hooks.

References

  1. I like lists and bullets and I am not AI. Tautology.town is written by hand! I like em-dashes too, but that battle has been lost. 

  2. “Parameter” and “argument” can be conflated, but strictly speaking a parameter is the name in the function definition and argument is the actual value supplied. That distinction is important here.