|
|
|
|
|
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. |
|
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/