Hacker News new | ask | show | jobs
by captainmuon 1574 days ago
I really don't like hooks, because they are so magic. The old class based way of doing things was much more explicit. At least, hooks should take some kind of "context" and "name" parameters so that they are in spirit a pure function. Then you could also call them in loops and if blocks without problems.

Actually, class-based components have some annoying magic, too. The type of the object you create when you write `<MyComponent>` in JSX is different from the component class you write. There is some wrapper around it IIRC.

I wonder what React would look like if you get rid of all the cleverness and hidden state, and keep JSX and the reconciler as only magic?

5 comments

The old class based way of doing things was much more explicit.

They weren't though. They looked explicit, but what was actually happening wasn't what appeared to be happening. Dn Abramov wrote a good blog post about the subtle bugs that can sneak into class components - https://overreacted.io/how-are-function-components-different...

At least, hooks should take some kind of "context" and "name" parameters so that they are in spirit a pure function. Then you could also call them in loops and if blocks without problems.

Dan also addressed a lot of the 'why are hooks like that?' questions in another post that goes into some of the designs the React team rejected. https://overreacted.io/why-do-hooks-rely-on-call-order/

Hooks can be hard to reason about but they make code a bit less error prone because when they don't work they fail completely. Classes don't. Classes work most of the time. That is so much worse.

The way hooks are handled when invoked in functional components is magic, as all stateful things in react are, but hooks themselves are very straightforward. Once you've written a custom hook, it's obvious that they're basically just (yes, this is an oversimplification) react components without the render step. You use the React API just like any other component, including using hooks, and then return some piece of state or whatever is needed. Like functional components, they're just functions that run top to bottom when the props change.
The old class based way of doing things was a slap in the face for anyone expecting a "reactive functional ui library" and it put me off react until they did the proper hooks implementation.
Hooks are more explicit for the uninitiated. Understanding the semantic meaning of when arbitrary method names are invoked throughout the component render cycle requires more investment in react's documentation than intuiting the logic of imperative function calls like "setState" in the body of functional component.
There are a lot of similar feeling alternatives beyond react. For example SolidJs is jsx based and ditches also the reconciler (modulo lists). It has a lot of cleverness in what it does with that jsx, but the result is way more straight forward and composable.