r/reactjs • • Mar 06 '23

Were React Hooks a Mistake?

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

29 comments sorted by

64

u/Mallanaga Mar 06 '23

Are click bait titles annoying?

28

u/apex_17 Mar 06 '23

I miss self binding “this” to all my variables… /s

-27

u/smirk79 Mar 06 '23

Do you not know how to use a lambda or are you being intentionally obtuse?

11

u/xroalx Mar 06 '23

=> wasn't always a thing.

3

u/buffer_flush Mar 07 '23

Do you even .bind() bro?!

6

u/PatchesMaps Mar 06 '23

I'll add a tldr for you: "hooks are bad because I write bad code."

Idk if this is an "official" best practice or not but I strongly avoid using useEffect to directly render UI. All UI rendering should happen in the return.

9

u/nabrok Mar 06 '23

I just skimmed this after realising that all the "problems" are solved by setCount(current => current + 1).

Did I miss anything?

2

u/jakelazaroff Mar 07 '23

Hi, author here! That’s not the problem — the issue is that the setTimeout sees the stale value of count (for the components with hooks). The call to setCount works fine!

1

u/nabrok Mar 07 '23 edited Mar 07 '23

I looked over it in more detail and it's an interesting problem. I'm not sure how often such a thing would come up in a real project though.

Anyway, another way it could be done is with a reducer ...

import { useEffect, useReducer } from 'react';

function reducer(state, action) {
  switch (action.type) {
    case 'START': return { initialized: true, started: true, count: 0 };
    case 'STOP': return { ...state, started: false };
    case 'ADD': return { ...state, count: state.count + 1 };
    default: return state;
  }
}

export default function App() {
  const [ state, dispatch ] = useReducer(reducer, { initialized: false, count: 0, started: false });

  useEffect(() => {
    if (! state.initialized) return;
    if (state.started) return;
    alert(`Score: ${state.count}`);
  }, [state.count, state.started, state.initialized]);

  const onClick = () => {
    if (state.started) return dispatch({ type: 'ADD' });
    dispatch({ type: 'START' });
    setTimeout(() => dispatch({ type: 'STOP' }), 5000);
  };

  return <div className="App"><button onClick={onClick}>
    { state.started ? 'Click' : 'Start' }
  </button></div>;  
}  

I suppose you could put the alert in the reducer function instead of in useEffect, but I think it's more appropriate for it to be in useEffect.

You could also write the above with a single useState, but I think the reducer is neater in this case.

Not saying this is a better way, just a different one.

3

u/rainst85 Mar 06 '23

LoL, I remember the day I figured how fundamentally important this is and I felt like I just became a true chad react developer

1

u/the_real_some_guy Mar 06 '23

Oh good, I thought this example was very much answer looking for a problem. Maybe there is a better example and I’m just not getting it?

4

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

I would not say a mistake, but hooks are not perfect. What I like:

  • useEffect and useMemo. Both are super great with the dependency array and a lot easier than comparing previous and old values.

  • it is easy to write custom hooks as composition of integrated hooks.

But:

  • useCallback sucks. I think callbacks passed to other components should be stable, because it can cause a lot of issue in combination with useEffect. useEvent could solve this problem, but I don't like that you have more code for that.

  • useRef is also annoying. Why do I need another hook just to have a normal stable variable?

3

u/lIIllIIlllIIllIIl Mar 07 '23 edited Mar 07 '23

I'm a useRef enjoyer, not as much as this guy, but close.

useRef is a misunderstood hook. Its puprose is different from useState. useState is meant for asynchronous updating the UI state, while useRef is meant for synchronously updating values used in callbacks.

Refs are great and you shouldn't feel bad for using them.

I haven't tried them yet, but signals feel like a combination of useRef and useState. They are synchronous (like useRef) and update the UI (like useState), so you can use them during both render and callbacks. It's great. It's likely a better default than React. However, I don't think it's mindblowing. Writing a custom hook in React that behaves like this is trivial. Solid might be more performant, but the mental model is the same.

I think the biggest villain here is useEffect, which is a great hook, but has been overused a lot. useEffect is also likely the reason for useState's asynchonicity.

2

u/jakelazaroff Mar 07 '23

I agree with basically every word of this! The thesis of the post is that with class components we basically got useRef for “free” because we had access to this, and IMO that’s what appeals to people about other frameworks that use signals, too.

1

u/sebastianstehle Mar 07 '23

I like it as well but it does not feel good. useEffect and useMemo really add features and make things easier, but for me useState and useRef do not. It feels like it should not be needed to use framework code for that. But I have to admin that I do not have a better solution.

2

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.

3

u/superluminary Mar 06 '23

Reluctantly, I do actually agree. Hooks take a lovely pure function and convert it into a sort of hybrid with some of the data magically injected from a secret source. The “rules of hooks” conceal the fact that this secret source is actually just an array. They’re not actually functional, they’re a sort of a mixed up hybrid between functional code and OOP.

I mean I still use them, but I don’t think we’ll be using them in five years.

7

u/jayroger Mar 06 '23

"Functional" in React context just means "uses functions, not classes". It doesn't have the same meaning as "functional" in "functional language". It's a bit confusing, but you can't hooks by comparing them with something they were never supposed to be compared to.

2

u/superluminary Mar 06 '23

Pure components can be properly functional though. They receive props and return DOM.

2

u/Parkreiner Mar 07 '23

This is why I like to distinguish between "function components" and "functional components". React's type library also doesn't call them functional components. I think that's usually a point of confusion for new developers – they're stuck wondering if what they're doing is "functional" in the traditional sense of the word, versus React's definition of "functional", which usually means "do something impure on the first render (setting up state), but then stay relatively pure for all future renders (the state is already set up, so it can be treated as a read-only value during rendering)".

1

u/Ebuall Mar 06 '23

It is still functional in FP context. React is very much coming from purely functional programming. Hooks are just trying to imitate Algebraic Effects with the languages we have right now.

2

u/smirk79 Mar 06 '23

It always seems to come back to Mobx. Someday people will realize how fantastic that library is.

1

u/superluminary Mar 06 '23

It’s genuinely amazing. It’s uncool right now because classes are uncool. Give it a few years and we’ll come back round.

2

u/MehYam Mar 06 '23

Mobx doesn't actually require classes, its just that a class and its constructor are convenient places to set up observable state. Akin to how deconstructed arrays and objects on the stack are the convenient way to access hook components.

2

u/superluminary Mar 06 '23

True. I’ve found it most convenient to use with classes though.

Data storage is an absolutely perfect use-case for OOP. I think we’re collectively going to remember this soon.

1

u/[deleted] Mar 06 '23

No