r/javascript • • Mar 06 '23

Were React Hooks a Mistake?

https://jakelazaroff.com/words/were-react-hooks-a-mistake/
7 Upvotes

24 comments sorted by

11

u/Exoskele Mar 06 '23 edited Mar 07 '23

Hooks are much easier than class components were for 80% of use cases, but the remaining 20% can be a bit hairy if you aren't so familiar with how the underlying system works. I ran into this exact kind of issue when doing mouse move events recently because I was using addEventListener in the component and getting stale state references.

Ultimately useRef is a good way to solve the problem.

1

u/[deleted] Mar 07 '23

I ran into this exact issue the other day while trying to get mouse move events from the document object. I wanted to increment a counter in my React state based on the mouse moves, but I kept getting the same old state in my event listener, which meant I was just incrementing on the same old value and got stuck.

I did use useRef to store a copy of the state, but it seemed like a very hacky workaround, having to duplicate the state essentially.

Is there a better way to use useRef than the way I am doing it? I really just want to use mouse move events on document to implement draggable elements.

1

u/RSveti Mar 07 '23

Maybe this could help you: https://beta.reactjs.org/reference/react/useState#setstate

Basically setState takes a function which gets called with latest state.

1

u/[deleted] Mar 08 '23

Thanks! So I did a test using the updater function. Basically I am making a little dial knob component (similar to what you see in digital audio workstation software). The knob has a value and you can change that value by clicking and dragging on it.

The problem with using the updater function is that I can only access the latest state within the function context, which means I can't do things like call a callback prop that passes the knob value back to the parent because React will complain that I am attempting to re-render a parent and its child at the same time.

Now the argument can be made that I should make the child component be stateless, but then that means that whatever callback prop the parent passes into the knob has to accept an updater function. This means that some aspects of the knob implementation is leaking into the parent, which is less than ideal.

1

u/RSveti Mar 08 '23

I would make it so that knob just calles onChange function and passes in direction and amount that it moved and then its parents job to update the state. And now there is no leaking of responsibility.

1

u/[deleted] Mar 10 '23

Passing just the delta back out of the component does "fix" the leak, but it also makes the component's interface less than ideal because when you think about it, what do you really want from a knob? Just the value that its currently set to, not the delta of the value from the previous value. You're sorta making the parent do more of the lifting than it really should and if all consumers of this knob component now have to worry about adding this delta to whatever they think is the state, it gets a bit cumbersome over time, especially if this component is used a lot.

I wish there was some react-compatible way to register DOM EventListeners. Like maybe a React.document.onmouseover or something. I don't know, maybe not possible, but still, it would make custom components a heck of a lot easier to do if you could.

Thanks anyways for all the suggestions! I've always wondered when I would ever use state updater functions and now I know.

11

u/shuckster Mar 06 '23

Those are some hot damned beautiful ass fonts on that blog.

As for Hooks, I think their main drawback is it's far too easy to do a whole bunch of business-logic with them. There's a tendency to overuse them for updating state, rather than merely responding to updates of it.

It's not uncommon to see a trampoline of useEffects updating state all over a mildly complicated component, completely betraying the nature of what a component should be: A pure function that represents state as UI, optionally sending events to interested subscribers when the user does something.

While it's falling out of favour due to boilerplate issues, the core idea of Redux sensibly expresses this idea, and solutions to untangle spaghettified business-logic would do well to follow its example.

If you have more than one useEffect in your component, it's probably a signal (no pun intended) that it's time to take a good look at your business-logic and take steps towards lifting it out of there so you can reason about it without worrying about those infernal "rules of hooks".

As for signals themselves, if they don't encourage us to place business-logic in the right place I would guess they will eventually suffer from their own problems. The management of wild state dependency-graphs woven throughout the UI of complex apps, for example.

But hey, if programming were easy everyone would be doing it.

3

u/jayerp Mar 06 '23

I try to limit my usage of hooks to UI state change logic, business logic I do somewhere else.

3

u/jakelazaroff Mar 07 '23

Post author here. You just made my day — thank you so much!

2

u/shuckster Mar 07 '23

I'm glad. Thanks for the article!

1

u/eternaloctober Mar 07 '23

doing HTML5 canvas programming is one place where useEffect can get a bit crazy. a simple way to do canvas in react is to draw all the stuff in a useEffect. but then you need a very long list of things in the useEffect that are relevant to your drawing code. I made an alternative system that actually redraws the canvas using mobx now, which is quite a bit nicer as it automatically tracks the relevant things. note that there are alternatives like react-konva that add a delcarative api to canvas but haven't really evaluated it

0

u/dark-king_Ray Mar 06 '23

Can you explain what you mean by business-logic

1

u/shuckster Mar 07 '23

Business-logic is code that makes the program go.

I also asked ChatGPT to help explain it:

In software development, business logic refers to the part of an application that manages the business rules and processes, determining how the application should respond to user inputs and other events. This includes things like calculations, data validation, decision-making, and other core operations that are essential to the functioning of the application.

Pretty good.

As for how it relates to my original point, here's what I was getting at:

Take the following diagram:


      +-----+    +----+    +------------+
  .---| App |--->| UI |--->| User event |---.
  |   +-----+    +----+    +------------+   |
  |                                         |
  +------<-----------<-------------<--------+

Obviously the devil is in the details, but ideally speaking a UI is merely one way of representing your App. Nearly all the business-logic should live in the App, and the UI just renders its current state and posts events when the user does something.

Now, if you sprinkle your business-logic throughout your UI code you can imagine how the simplicity of the above representation is lost.

An "App" is already doing a lot of complex stuff, and will be full of its own little flows you need to reason about. Modular UI design, ie; just deciding what components to have, is also not trivial, and filling up components with business-logic makes it hard for us to see how they could be simpler, more reusable, and less prone to error.

4

u/BerryNo1718 Mar 06 '23

Honestly that issue is pretty specific to setTimeout and setInterval given their nature. But you can create a useTimeout hook which doesn't suffer from the same issue.

See: https://usehooks-ts.com/react-hook/use-timeout They solve the issue by saving the callback in a ref. All the hooks in that library are well thought and cover common pitfalls like that. Don't try to do it yourself, you'll likely mess it up.

4

u/roofgram Mar 07 '23

useState, useCallback, useMemo, useRef, etc.. are all kind of hacks because you can't store state in a functional component itself. Plus the fact that closures wrap old state result in failure cases you will eventually hit like in this blog post. I've definitely had to revert to class components a few times because of this and it makes me think if usings were a mistake. Classes were more code, but nothing magic; functional components are smaller but need a lot of this 'using' magic to work.

10

u/ILikeChangingMyMind Mar 06 '23

Have you tried programming with class-based React code?

I have, and I promise hooks were not a mistake: if they were, we'd all still be using classes.

4

u/card-board-board Mar 07 '23

Classes with redux and HOCs were a nightmare, and they didn't create an environment to write clean concise code. That being said useEffect, useMemo and useCallback have always felt like hacks. I would prefer to write a function then call that function, not write a function and have it call itself whenever I call a different function to update a variable. I think I'd have rather just had JS classes be less weird than end up with functions that are more concise but follow mystical magical rules.

-1

u/[deleted] Mar 06 '23

Whoa whoa whoa let's stay above the belt here. Classes were a mistake from jump, but let's keep it classy but classless 😂

0

u/ILikeChangingMyMind Mar 06 '23

I honestly didn't think there was anything "unclassy" about my comment.

-1

u/[deleted] Mar 06 '23 edited Mar 06 '23

It was a joke, that's why the emoji

Edit: also a play on words not a pun

-13

u/GrandMasterPuba Mar 06 '23

Yes, hooks were a mistake. No, Solid and Vue are not any better.

0

u/[deleted] Mar 06 '23

[deleted]

7

u/rk06 Mar 06 '23

React was a definite improvement upon existing paradigm. Angular js already had support for components. But they prioritized directives. React forced the component oriented approach.

Hooks too are a great idea. React's implementation of hooks is faulty. Vue and solid do not suffer from those issues

5

u/markus_obsidian Mar 06 '23

React just lived long enough to become the villian.