by xixixao · 4y ago · 0 comments
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.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.
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’.