|
|
|
|
|
by recursive
629 days ago
|
|
I have a pretty thorough understanding of both. But I can't understand how you'd find them to be similar in any way. Functions forming closures can be called conditionally, in a loop, or even when no react component is even rendering. Most of the complexity of hooks is not addressed at all by closures, and I don't really what part of their behavior is related at all. Maybe just that you can pass a value to one function, and then get it returned from another one. The standard hooks delegate to a dispatcher, which has access to the current fiber. The current fiber has a linked list of memoizedState for the current work node. It's true that a lot of the functions that eventually service the hook calls do contain closures. But that doesn't seem to grant much insight into how to use them or how they work. It's like saying "if you have an understanding of loops, the reconciler is quite intuitive". I mean yes, the reconciler uses loops. But the behavior of reconciliation may still be quite mysterious. |
|
I think of React components as not closures but coroutines (and hooks are its yield points).
Hooks are implicitly keyed by index which is the most magic-y/surprising part... but I'm sure if you had to manually key them that'd be criticized too (and would be abused to death-by-bugs, so I can see why they went with this design).
If you understand both points above, you understand hooks.
I still fail to get the (usual) criticism of hooks. They have lots of warts but the API (which is often what gets mentioned) is the most superficial and less annoying criticism. Feels like something that would be mentioned after just skimming the docs. Very shallow.
On the contrary: useEffect is a footgun and deserves criticism. useRef being overloaded to mimic instance variables is confusing for newbies (but this is just a naming issue IMO). The difference between normal/layout/insertion effects is complex and subtle. The new stuff that tries to solve some issues with the concurrent mode (like transitions/deferred value/etc.) feels like a huge hack.
React 19 will come with its own warts (actions, RSC...)
But the API? I don't care at all. Pretty simple, at least for my mental model.