5 ms·
> the only way to implement them (that I can think of) is messing with global state What do you mean?
by erikpukinskis 7y ago
> the only way to implement them (that I can think of) is messing with global state
What do you mean?
- ratww 7y agoA regular global variable that is incremented each time you call useState/useEffect/etc and is resetted every time a new component starts rendering. This is why hook order must be maintained. I have no idea where this is implemented in React, but in Preact it's a simple integer that is incremented: https://github.com/preactjs/preact/blob/abc162c4d6442d5495f6aaba5d31c2bc75a3869b/hooks/src/index.js#L107 https://github.com/preactjs/preact/blob/abc162c4d6442d5495f6... I think there are other ways to implement them, such as treating the return of the render function as an AST and turning hooks into dumb factories, like a free monad. But considering the constraints they have (the need to maintain order) and the way it works (the fact the render function runs multiple times), I'm guessing it's just the same solution as Preact.
- brlewis 7y agoResetting it as render starts makes that number conceptually local to the vnode, even though preact's implementation involves a variable that's global in the context of that module.