Hacker News new | ask | show | jobs
by azemetre 1373 days ago
Hooks are executed in order as they are defined, isn't that a fundamentally broken design in regards to language spec?

I don't have an opinion, just generally curious because it feels very odd that the order of my functions matter.

2 comments

> Hooks are executed in order as they are defined

Hooks are functions, and they are executed in the order called from within the component, which is itself a function, just like any other functions calls from within another function.

(The mechanism tracking calls to them and deciding whether the function passed to the hook needs to be called requires them to be called in the same order each time the component is executed; if they were called in order of definition rather than normal execution order this would be true by definition; the whole reason for the rule about not using flow control around them is that they are functions executed in normal flow order.)

Thanks for the correction and teaching me something!
It only matters that the order not change dynamically between renders. This probably could have been avoided if react required a unique key per hook, but I think for brevity it's a decent trade-off.
For the life of me, I can't understand why they didn't go the route of "add an id to your hook." It would solve one of the two big gripes people have with hooks.
ids would be stuttering (especially for things like useMemo/useState), add a different source of error, and—if the goal was to make hooks compatible with flow control—probably create new categories of bugs that would be harder to catch in a linter or even with runtime checks like the existing “number of hooks cllaed changed” one.

Adding visual noise to enable subtle bugs may not be a win.