r/programming • u/pmz • Mar 12 '23
Were React Hooks a Mistake?
https://jakelazaroff.com/words/were-react-hooks-a-mistake/25
Mar 12 '23 edited Mar 12 '23
Those examples aren’t equivalent, timer still has to be removed on dismount.
"Oh but I dont need it", some say
And thats how you get bugs 2 months later, when the component is used in an unexpected way.
But remember that
countisn’t a value itself — it’s a function that returns the current state of the signal.
That’s the main reason I dont like signals. In any non-toy example you'll need to pass values to external libraries, and end up with wrappers-within-wrappers because a library doesn’t care about signals - it needs a value. Signals require more glue code.
While a similar case could be made against useMemo/useCallback, the difference is that these arent needed - they’re purely an optimisation; I expect some future StrictMode to ignore them all together.
6
u/musical_bear Mar 12 '23
Curious - what do you mean by useMemo and useCallback not being needed? What happens if some function is a dependency in an effect dependency array where calling that effect is extremely expensive and you wish to only call it when absolutely needed (whenever the function changes in some way that affects its output).
4
Mar 12 '23 edited Mar 12 '23
It would be slower in development mode, but it always has to run during first render anyway. I dont see re-running on a re-render as a problem.
The mental-model I use — it should be "safe" to re-run an effect at any time, as if the dependency array was not specified. Treat it as an optimization, not a guarantee. Following that, new values from
useMemo/useCallbackwont break anything.In the blog post's example, this can be achieved by managing the timer outside of react, and the component only subscribing to the timer. Subscription becomes the effect, not the timer.
The legacy docs describe the dependency array as an optimization, but the new docs dont use that wording. Ideology behind
useEffecthas changed since release as well, I'm not sure if my interpretation is still correct.
11
u/bigorangemachine Mar 12 '23
I think author is missing some part how hooks works.
Hooks is dangerous to use ref's like that. You should only use Refs for actual refs and things that need to be set on initalization that should not create a re-render.
If you debug hooks you can get re-renders that never display. So you may get a component execution on something that was never meant to be rendered. Each time the component runs the state & props flys through the combinations its been updated into in that frame.
The problems with classes is React has to support the shouldComponent render which adds extra & unnecessary checks on each frame.
7
u/turkish_gold Mar 12 '23
The problems with classes is React has to support the shouldComponent render which adds extra & unnecessary checks on each frame.
There is a misconception that function components are somehow faster than class components. They are not. I may, in theory, be possible to do certain optimizations with them but the React team hasn't done so (at least by 2021 when I last checked).
22
u/dzhmrglj Mar 12 '23
First - I find it hard to take seriously someone who uses the monospaced equivalent of comic sans. That being said, I managed to get through the end, last paragraph sums it all up pretty nicely - time will tell.
My opinion is that they weren't a mistake. Majority of the complains and issues with hooks I've heard revolve around issues with useEffect and a confusion with context/custom hook relation, followed by the question on number of rerenders caused by changes in contexts.
I'd draw a parallel here between hooks and coffeescript - I passionately hated coffeescript for a number of reasons, but I must recognize its significance of bringing a transpiler to the JS game and effectively getting more people to think outside the box so now we have things like Babel or TypeScript. For better or worse, opinions may vary :)
CoffeeScript wasn't the first something-to-javascript language, but it's the one that has made (in my opinion) the most impact on modern frontend development.
4
u/SPBesui Mar 12 '23
I never used CoffeeScript much, and didn’t really enjoy it when I did, but I love the influence it had on JS. It’s amazing is how fast it died out. I think it was mostly a result of 1) ES6 being standardized with many CS-inspired features, and 2) VS Code (with heavy TypeScript focus) overtaking Atom (a large, open codebase written in CS).
4
u/dzhmrglj Mar 12 '23
6to5, now known as Babel, also played significant role in coffeescript’s demise :)
1
Apr 16 '23
Thing is, Hooks would be sooo much better if React just shipped a compiler but they want to stretch their "its just S -> V JS functions" branding to its limit
8
u/satcollege Mar 12 '23
Pure functions with rerenders >>>>>>>>>>>>>>>>>>>>>>>>>> signals. It's like y'all have never had to work with a legacy reactive codebase.
3
2
u/ironbody Mar 12 '23
Is there really no way to make that game component without useref? That seems like such a big oversight by the react team.
3
u/tswaters Mar 12 '23
You'll either get a stale
countvariable in the alert (it will be the value as it was when it was first called), or you passcountin the dependency array, so each change tocountsets up a freshsetTimeout, giving the user another 5000ms.Refs exist outside the lifecycle of rendering and dependency arrays so you can put a value somewhere and pull it out later. using refs in the dependency array of useEffect has no effect. At least, it shouldn't... the
react-hooks/exhaustive-depscomplains about it anyway.One way might be a separate state variable for "finished" which the setTimeout callback sets to true - a separate useEffect with
[finished, ccount]could alert the current count value if finished is true.Actually, I tried this out and while it seems to work, sometimes the "alert" messes with things and react will raise an exception, "Uncaught Error: Should not already be working.". Changing it to a console.log works as expected, always. Probably because alert blocks main thread?
Here's one that works without refs -- but, notably it needs to run that second useEffect with each change to count so signals would likely be more efficient. In this example, probably negligible but in more real-world cases all those functions might add up.
function Game() { const [count, setCount] = useState(0); const [started, setStarted] = useState(false); const [finished, setFinished] = useState(false); const handleClick = () => { setCount((prev) => prev + 1); setStarted(true); }; useEffect(() => { if (!started) return const tid = setTimeout(() => setFinished(true), 5000); return () => clearTimeout(tid.current); }, [started]); useEffect(() => { if (finished) { setCount(0); setStarted(false); setFinished(false); console.log(`Your score is ${count}!`); } }, [finished, count]); return ( <button onClick={handleClick}> {started ? "Current score: " + count : "Start"} </button> ); }
2
u/GrandMasterPuba Mar 12 '23
The problem with hooks is not their concept, but their execution. They're based on the idea of algebraic effects, and would work fantastically in a language that actually supported such a paradigm.
But JavaScript is not that language, and as a result it crumbles under the sheer number of leaks the abstraction of a hook opens you up to.
2
u/draculadarcula Mar 13 '23
I’m slowly coming around to react (ex Angular) but have always felt the hooks were just generally not intuitive and a bit hacky feeling. Class components were not “better” but certainly more intuitive when I did them way back when. I love a lot about react but the way you manage state just feels over-engineered and odd.
2
u/Tarmen Mar 12 '23 edited Mar 12 '23
Is react even fundamentally different from signals? Like, if it's identity tracking for rerenders were better this all wouldn't really be an issue.
The jetpack compose compiler supports everything signals do, but you can still do react-style pure state. It makes this reliable using some extra transformations such as turning
foo(() => { count.value += 1 })Into
let lam = useMemo(() => { count.value += 1 }, [count])
foo(lam)So maybe the react compiler stuff could actually fix hooks? Though a slightly extended useState API with a function to read the value in the currently committed transaction would be nice as well.
1
u/gc_DataNerd Mar 12 '23
As opposed to needing to know the dozens of lifecycle functions and needing to split your implementation across them. Hell no
1
u/possiblywithdynamite Mar 13 '23
The only issues I've run into with hooks are where I need to reference state in a function called inside an onMount-only useEffect. It's a huge pain in ass when building chrome extensions because I'll often need to add an event listener somewhere in the real dom and the callback of the listener ends up with a stale reference to state. The issue is explained here along with the not-so elegant solution using refs: the impedance mismatch
-3
u/fagnerbrack Mar 12 '23
Neither signal or hooks, use your domain models. State Management is not a "thing" that you must generalise.
Each business domain models have their own mechanics that differs from each other, "state" is merely something you may (or may not) end up doing in many different ways depending on the requirements of your design and your business domain.
0
Mar 12 '23
[deleted]
13
u/recursive-analogy Mar 12 '23
True story: once worked with a dev that used comic sans. Not as an edgy joke either.
14
u/sidit77 Mar 12 '23
There is a monospaced version of comic sans called comic code that is unironically amazing. It's my favorite programming font at the moment.
20
u/Strange_Meadowlark Mar 12 '23
An unexpected advantage of Comic Sans is that it's legible to individuals with dyslexia -- the letter shapes are asymmetrical and inconsistent (i.e.
u!= rotate(n, 180deg);p!= flipX(q)), which makes the letters individually distinguishable.I wonder how well Comic Code retains this trait. I see the designer uses the serifs to keep
dfrom being a perfect mirror ofband theMhas straight verticals while theWopens outward at the top. But I don't suffer from dyslexia so I can't judge whether it's effective.2
u/r00dimental Mar 13 '23
This is (sort of) correct. Researches are agreeing on the importance of the spacing of the letters, not the letter shapes.
They also stress that this area needs more research.
-3
u/Vexal Mar 12 '23
javascript is basically a joke language anyway so comic sans suits it.
4
Mar 13 '23
I mean sure it's weird but it's still necessary for the current entire functioning of the internet lol
-1
-4
u/Character-Education3 Mar 12 '23
Word. I still hold that it looks like a high schooler created it and put in a bunch of unnecessary braces, semi colons, and what not to make it look "more code-y".
1
u/nacholicious Mar 13 '23
Comic sans is a great font for dyslexics because the characters look very different from each other
53
48
u/haikusbot Mar 12 '23
Who the fuck uses
An italic font like that
In their editor?
- ReallyGene
I detect haikus. And sometimes, successfully. Learn more about me.
Opt out of replies: "haikusbot opt out" | Delete my comment: "haikusbot delete"
15
u/jacolack Mar 12 '23
Good bot
18
u/JimK215 Mar 12 '23
the best part is that it wrote the haiku in italics
1
u/SPBesui Mar 12 '23
Icing on the cake
The poem in italics
Haikus are the best
1
u/miramichier_d Mar 13 '23
Icing on the cake
It's written in italics
Haikus are the best
I fixed that for you
I added a syllable
Learn how to haiku
:)
1
u/SPBesui Mar 15 '23
While I do like your version better, and respect the fact that your commentary was also a haiku, you didn’t actually add a syllable. “The poem” = 3 syllables; “It’s written” = 3 syllables. Same same.
1
u/miramichier_d Mar 15 '23
I'll have to concede this one as there are in fact several dictionary definitions that indicate that "poem" is two syllables. Although there are other dictionary definitions that have it as one. I'll consider my original comment as mostly unnecessary.
1
1
u/Lalli-Oni Mar 13 '23
I think you might be missing the point, obviously its not global, here its only on language keywords. Now this is just an armchair theory but keywords are mostly inferred by our brains. Using different fonts might help us skim the code.
It's basically another dimension for differentiation of code highlighting.
0
Mar 13 '23
[deleted]
1
u/Lalli-Oni Mar 14 '23
My point is specific to keywords. This is very debatable ofc. But I think we rarely read language keywords when we are experienced with the language. I don't need to read the
ifto recognize an if statement.So making it harder to read or just stand out might help our eyes and subconscious focus on the parts of the code that might be more "important".
Basically if we don't actually read certain text, the cost of making it hard to read is mitigated, and perhaps surfaces different value.
That being said, this is splitting hairs XD and seeing as its a blog article (although fairly high level, can assume readers to be very experienced in
js) I'm starting to agree with you while explaining my point, though :þPS: I guess being pedantic it's not that the font is italic, but perhaps cursive? If it was only italic its not so hard to read as you say.
0
Mar 12 '23
[deleted]
17
Mar 12 '23
Things being immutable is soooo much easier in the long run.
I would say Rust-style mutability is even easier. Not an option in JS of course but I'm just saying pure immutability isn't the pinnacle.
116
u/[deleted] Mar 12 '23
I miss self-binding "this" to every variable in my code.