Re:Thinking in React Hooks
by baddox on Thursday December 12, 2019 @01:48PM
(#21774916)
I’m genuinely wondering why the fact that the order of hooks needs to stay the same between successive invocations of your function component is considered a bad or confusing thing. The complaint comes up a lot, so I know that it bothers people, but I haven’t been able to understand why.
[ Parent
| on HN ]
I can sympathize with people that find it confusing, because it is an unusual requirement considering they're simple function calls. The fact that the only way to implement them (that I can think of) is messing with global state is also a very strange in today's functional-centric programming world.
But on the other hand I agree that "keep the order!" is a very simple request for a feature that is so useful.
Re:Thinking in React Hooks
by erikpukinskis on Friday December 13, 2019 @02:43AM
(#21779832)
> the only way to implement them (that I can think of) is messing with global state
What do you mean?
A 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/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.
Resetting 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.
Re:Thinking in React Hooks
by paulddraper on Thursday December 12, 2019 @05:35PM
(#21777317)
The most probable case of an issue is putting then inside a conditional block.
Re:Thinking in React Hooks
by erikpukinskis on Friday December 13, 2019 @02:45AM
(#21779841)
Just put the conditional inside the hook.