Hacker News new | ask | show | jobs
by xixixao 1569 days ago
Interesting take, but I find it much more insightful to think about how you’d simply implement a hook (not any of the React specific ones). MobX uses similar mechanism.

user declares foo with a call to “useState”

  function useState(…) {
    useStateCalls.push(…)
  }

  useStateCalls = []
  foo()
  // do something with useStateCalls
It’s a neat syntax sugar, it explains why they can’t be called conditionally, it allows for a clean api. If every component received a “hooks” argument, like this:

  function BazComponent(props, hooks) {
    hooks.useState(…)
It would be less magic, more boilerplate (especially with custom hooks). That’s it really.
2 comments

Agreed that the actual implementation of hooks is _relatively_ "simple" internally. I strongly recommend Shawn Wang's talk/post "Getting Closure on Hooks" [0] as a good dive into the implementation approach.

That said, `hooks` as an argument wasn't chosen for a couple reasons:

- It doesn't work for custom hooks, which need to be written as separate functions

- Function components still receive the legacy `context` object as their second parameter. (The long-term migration plan is that someday they will instead receive a potential `ref` object instead, and that will allow removing the `forwardRef` API.)

Dan Abramov wrote an extensive post on why various alternative hook API designs were rejected [1], including the design criteria and constraints that they were looking for.

[0] https://www.swyx.io/hooks/

[1] https://overreacted.io/why-do-hooks-rely-on-call-order/

For me the issue is whether the magic is fully acknowledged and explained by the project, bringing me in on the details of the compromise.

I tried to get into MobX years ago but found it impossible to get along with. I don’t know what it’s like now, but the documentation back then failed to explain the magic. It was just like “Hey, look how convenient this is, just follow our instructions and you’ll be fine (and don’t think about how it works)”.

Then some time later React came out with hooks, and they took the time to introduce the concept carefully, to explain how it’s actually really weird and non-idiomatic and principle-breaking but leads to all these ergonomic benefits, just make sure you understand the weirdness and keep it contained. They give you the information you need to change it in your head from ‘magic’ to ‘smart compromise’.