You may see the title and wonder: why do this? react hooks is a useful invention that reorganizes the paradigm of writing and thinking about code, using smaller abstractions to split state and functions by function rather than centralizing them into a single state or lifecycle. But react hooks suffers from the notion of state dependencies, and worse: it relies on manual management - despite the official eslint rules provided by react, if you’ve used it, you’ll find it has a high rate of false positives - especially in complex components. So, does this mean that there is no solution? No, the author of vue3 spoke in one of his talks about the improvements of vue3 hooks over react hooks, one of which is that you don’t need to manually manage dependencies, watch dotJS 2019 - Evan You - State of Components. But react is really better in terms of ecology (including various libraries, IDE development experience), so I tried to implement automatic dependency management in react somehow, implementing some primitive hooks that behave similar to vue3.
When it comes to variable state in react, mobx is probably the easiest one to think of (as opposed to the immutable redux), so the following is based on it to implement the above hooks.
I wasn’t able to fully implement the vue3 hooks for a few reasons, for example
- need to wrap functions that manipulate state with
useVFn, whereas in vue3 it’s really just a matter of declaring normal functions in the setup function
useWatchuses a computed function, while vue3 uses an array of dependent states
- You must use
defineComponentto wrap components, in vue3 it’s just a hint for code
The react ecology does have a variety of things, and the ecology is super rich, but certain details are really done relatively rough, especially with the official laissez-faire. I’ve often wondered why no one feels weird about the current stuff. For example, react-router v4=>v6 is not updating properly, material-ui/fluentui’s form and table components are almost unusable compared to antd, the complexity of redux is still necessary as the default state manager, react hooks dependency management relies on manual annoyance. css in js dozens of options why official don’t care and so on.