News for hackers. Stuff that matters.
Re:Understanding UseMemo and UseCallback by worble on Tuesday August 30, 2022 @04:45PM (#32654818)
While I personally like React, I have to say the design of the library is just so awful and non-intuitive. While I can maintain a legible codebase myself, as soon as juniors in my work are involved I have to spend a lot of time reviewing PR's, fixing changes and explaining concepts in order to make sure that the application actually runs correctly and isn't, say, infinite looping in a useEffect or something like that.

I only rant about this here because I think useCallback is pretty awful design - separate functions that only exist as syntactic sugar are terrible for user readability. A lot of people probably know useMemo as it's quite easy to understand and used somewhat frequently, but if I were to use useCallback in my code it would probably cause a lot of others at my work to then have to go scouring the docs to figure what the heck this hook exactly does. On the other hand, just forcing users call useMemo and return a function means that everyone who knows useMemo knows what's happening.

Unless I'm completely misunderstanding how useCallback works, perhaps React actually does some extra optimization under the hood or for this or something.

Re:Understanding UseMemo and UseCallback by petilon on Tuesday August 30, 2022 @07:32PM (#32656529)
> I have to say the design of the library is just so awful and non-intuitive.

Absolutely agree. But this wasn't always the case. The original class components were much easier to understand. A backend developer could open a .tsx file and understand what is going on, and make simple fixes. This was one of the strengths of React - it was so clean, compared to Angular and other frameworks.

But then they introduced hooks and messed it up. Now it is not intuitive in the least. Hooks makes some things easier but the cost in terms of loss-of-intuitiveness is huge. The other mistake Facebook is making is assuming that performance is the most important attribute of a UI framework. It is not. For 99.9% of developers the original React was already fast enough. They should have focused on making the mental model cleaner, and smoothing some of the roughness of the lib such as updating the props of a stateful component, handling deeply nested objects in the state without making entire copies of the data and so on.

Re:Understanding UseMemo and UseCallback by HeyImAlex on Tuesday August 30, 2022 @09:23PM (#32657264)
I don’t think it was done for performance, hooks just compose much better than class components. Definitely a trade off in terms of blank-slate intuition, but it unlocked a lot of things in the realm of reusability.
Re:Understanding UseMemo and UseCallback by foomatic on Wednesday August 31, 2022 @12:33AM (#32658409)
What does "compose much better" mean?
Re:Understanding UseMemo and UseCallback by HeyImAlex on Wednesday August 31, 2022 @01:16AM (#32658640)
copy/paste from another comment:

Hooks compose, whereas side effects and memoized values sprinkled through component constructors and lifecycle methods do not.

For example, the equivalent of useEffect required calls inside of componentWillMount, componentDidUpdate, and componentWillUnmount. You try and make something like this re-usable and you’ll be leaking details of your implementation across the whole component via inclusion in these lifecycle methods, not to mention any data you’re shoving onto the component instance. But it’s still doable.

Now, what if you wanted to use this re-usable behavior inside of another re-usable behavior? It gets complicated fast! Now your library needs to expose the lifecycle-updating methods of the underlying library, leaking details all the way down. Hooks are opaque from the perspective of lifecycle, while still having access to all the same… hooks.

Re:Understanding UseMemo and UseCallback by foomatic on Wednesday August 31, 2022 @01:51AM (#32658841)
Oh ok. I'd agree Hooks compose much better then. But there was no attempt or consideration at compositional API for class based components besides getting rid of it entirely and then adding functions that hook into the nether nether.

> For example, the equivalent of useEffect required calls inside of componentWillMount, componentDidUpdate, and componentWillUnmount.

Yeah from what I recall this was the prime motivational example given in the React docs for introducing hooks. It's a legit problem. But hooks and getting rid of class based components is not the only solution. In classical OO are also well worn solutions along the lines of hooks, they just work with classes / objects with interfaces still. It's somewhat frustrating that this is never even considered.

Re:Understanding UseMemo and UseCallback by captainmuon on Wednesday August 31, 2022 @02:51AM (#32659190)
It depends, they compose better until they don't. It is easy to mess hooks up if you do not call them in the right order, especially if they are nested (composed) in other functions. You need discipline to use them correctly.

Ironically they could have prevented this by making them more functional. Instead of some magic hidden state, you should have to always pass a context to them, and you should have to give every hook a unique name or a Symbol().

Re:Understanding UseMemo and UseCallback by HeyImAlex on Wednesday August 31, 2022 @10:18AM (#32662349)
I know they considered “keyed” hooks, but that api is a lot more verbose since you need to key _every_ hook you use, and hooks internally need to create a sub-hook context / namespace to avoid collisions which either needs to be managed manually _or_ means you can’t use plain functions as hooks (there would be some createHook function you’d run instead).
Re:Understanding UseMemo and UseCallback by SPBesui on Wednesday August 31, 2022 @11:01AM (#32662939)
> The original class components were much easier to understand.

Class components only made you feel like they were easier to understand because the method names indicated an intuitive lifecycle. But the reality under the hood was almost certainly different than your mental model because the method/event handler names were actually deceptive. Hooks are much closer to the metal, so to speak.

> A backend developer could open a .tsx file and understand what is going on, and make simple fixes.

They might assume they knew what was going on and how their "simple fixes" would affect execution, but that would probably be naïve. But that goes for anyone jumping into any codebase for a platform/library that they're not familiar with.

> Hooks makes some things easier but the cost in terms of loss-of-intuitiveness is huge.

This is fair, although I feel like the learning curve for React is only steep at first, then plateaus for the vast majority of application developers. It only gets really complicated (as anything does) when you start to get into advanced performance tuning or you're writing a library with very specific requirements.

> The other mistake Facebook is making is assuming that performance is the most important attribute of a UI framework.

This is simply not true. The React team has indicated many times over the years that basic, hello-world level, idiomatic React code is fast enough for the vast majority of applications ("don't worry too much about the number of re-renders," etc.). They're very anti-premature optimization as a group.

Also, Hooks weren't introduced to improve performance anyway (at least that wasn't the primary motivation).

> handling deeply nested objects in the state without making entire copies of the data

It's not from the React team, nor is it specific to React, but have you tried immer? https://immerjs.github.io/immer/

Re:Understanding UseMemo and UseCallback by ummonk on Wednesday August 31, 2022 @04:49PM (#32668172)
See this is interesting because I always found it hard to keep track of the lifecycle and state changes in React classes (especially in actual production code which quickly devolved into a tangled mess) but found functions and hooks extremely intuitive and once they were introduced. And refactoring and composability became way easier.
Re:Understanding UseMemo and UseCallback by michaelsalim on Tuesday August 30, 2022 @05:11PM (#32655126)
While I agree with with that useEffect can be non-intuitive and easy to misuse, I think useCallback is pretty nice to have.

From what I'm aware, it's as you said. It's simply a syntactic sugar for useMemo if you want to memoize functions.

Now if useCallback doesn't exist, you have to use useMemo and pass in a function to the function. Something like `useMemo(() => () => ...)`. Sure if you know what useMemo does then you'll know what it does. But I have a hard time believing that juniors would find that easier to read than useCallback(() => ...).

All I need to say to them is: "Hey, if you want to memoize a function, use useCallback instead". And if I see useCallback used anywhere, I know for sure that it's memoizing a function. Rather than saying: "So you see that there's an extra bracket there? That means that you're returning a function. Yada yada"

There's a grand total of 15 hooks[1], most of which you probably never ever have to use. I would expect all React developer to go through them all to see what they're about.

I would also expect them to know & remember most of the basic ones: useState, useEffect, useContext, useReducer, useCallback, useMemo and useRef. That's a total of 7 functions. If they can't do that then I question the quality of today's developers.

[1] https://reactjs.org/docs/hooks-reference.html

Re:Understanding UseMemo and UseCallback by ummonk on Tuesday August 30, 2022 @07:57PM (#32656696)
> I would also expect them to know & remember most of the basic ones: useState, useEffect, useContext, useReducer, useCallback, useMemo and useRef. That's a total of 7 functions. If they can't do that then I question the quality of today's developers.

Exactly. I’d rather write the code myself than have to review the code of someone who can’t understand such a basic set of concepts.

Re:Understanding UseMemo and UseCallback by mmmpop on Tuesday August 30, 2022 @08:54PM (#32657083)
But see, you're not thinking enterprise.
Re:Understanding UseMemo and UseCallback by foomatic on Wednesday August 31, 2022 @12:51AM (#32658493)
"useCallback" is not very intuitive naming. I'd guess a fair bit of the confusion could be attributed to this alone. Could have been useMemoizedValue useMemoizedCallback at least. The whole useXXX naming convention is also unintuitive.
Re:Understanding UseMemo and UseCallback by adamredwoods on Wednesday August 31, 2022 @01:29AM (#32658716)
Or the term "side effect" (especially in a language that does not enforce return types): https://dev.to/ruizb/side-effects-21fc
Re:Understanding UseMemo and UseCallback by epmatsw on Tuesday August 30, 2022 @07:24PM (#32656469)
I’d argue that useReducer and maybe even useRef most people could get away without knowing.
Re:Understanding UseMemo and UseCallback by postalrat on Tuesday August 30, 2022 @10:34PM (#32657689)
useRef is pretty important. useReducer though could be removed and I wouldn't notice.
Re:Understanding UseMemo and UseCallback by michaelsalim on Thursday September 01, 2022 @09:39PM (#32685630)
I'm inclined to agree with you since I don't use useReducer as well. But there are projects that are littered with that -w-
Re:Understanding UseMemo and UseCallback by boredtofears on Tuesday August 30, 2022 @11:42PM (#32658129)
> as soon as juniors in my work are involved I have to spend a lot of time reviewing PR's, fixing changes and explaining concepts in order to make sure that the application actually runs correctly

I've never worked on a codebase where this isn't true regardless of what frameworks or libraries are used - that's kinda part of the gig.

Re:Understanding UseMemo and UseCallback by amand33p on Wednesday August 31, 2022 @02:51AM (#32659185)
Exactly. I don't know why people pick on only React for this. Any un-opinionated library or toll will have the same problem.
Re:Understanding UseMemo and UseCallback by solardev on Wednesday August 31, 2022 @03:08AM (#32659274)
IMHO (only), React is a bit too flexible/modular/unopinionated and asks you to reinvent a lot of wheels... everything from basic page routing to syncing ajax calls to loaders and states, etc. More opinionated or bolts-included frameworks have defined conventions that you're strongly encouraged to adhere to, and they work great for most use cases. And when you see that pattern again, you know what the intent is.

But with React, every dev ends up doing the same thing their own way, with subtle differences and subtle bugs, and then as turnover happens and frameworks become less fashionable, codebases get polluted by a mix of different dev and tool generations and it gets even harder to ensure correctness.

Using a more opinionated framework built on top of React, like Next.js, can solve a lot of those issues... until Next itself becomes unfashionable and the cycle starts again :(

Re:Understanding UseMemo and UseCallback by scrollaway on Wednesday August 31, 2022 @05:10AM (#32659994)
Yeah React is not meant to give you this layer. NextJS indeed does. Why do you care if it becomes unfashionable in the future? Pick one tool that fits your use case and run with it for its lifetime. If you need to learn something else 5 years from now, learn something else. I’ve been in software for two decades almost, I’ve always had to learn new frameworks and libraries, part of the job isn’t it?
Re:Understanding UseMemo and UseCallback by solardev on Wednesday August 31, 2022 @10:44AM (#32662673)
It's not that I mind learning new things, it's that React is so barebones everyone tries to make it complete by adding different things. One person likes redux, another mobx, another context... some like class components and others like functions, some use libraries and other use frameworks, etc. Sometimes all in one codebase if it's old enough. It's a lot harder to maintain over time than a more opinionated framework. I wish Angular won out, myself.
Re:Understanding UseMemo and UseCallback by boredtofears on Wednesday August 31, 2022 @02:21PM (#32666246)
It's all just javascript at the end of the day. What you're describing is exactly why many people like React.

> It's a lot harder to maintain over time than a more opinionated framework.

That's not true at all, that depends on the quality of the codebase the exact same as if it were built on an opinionated framework. I've seen plenty of bloated Rails codebases that were miserable to maintain.

Re:Understanding UseMemo and UseCallback by cageface on Tuesday August 30, 2022 @06:25PM (#32655933)
React works great for simple examples and small applications. When you try to build something complex with good performance then the difficulty goes almost vertical. It’s trivially easy to miss or break a stable reference somewhere and tank performance or show stale data.
Re:Understanding UseMemo and UseCallback by littlecranky67 on Wednesday August 31, 2022 @03:09AM (#32659280)
What other FE Framework does a better job at scaling up in your opinion?

I work as a freelance FE dev for 8 years and been doing webdev since the late 90s. I must say that for SPAs, React (with hooks) does the best job at scaling up (if you pay attention to your architecture) and I have seen and used frameworks/libs come-and-go such as knockoutJS, jquery, angular1, angular2+, (p)react etc.

Re:Understanding UseMemo and UseCallback by cageface on Wednesday August 31, 2022 @05:50AM (#32660194)
I haven't tried any of the other comparable frameworks at similar scale. Both Svelte and SolidJS seem much nicer than React to me on the smaller projects I've tried them on but I haven't used them on large enough projects to make a direct comparison.
Re:Understanding UseMemo and UseCallback by amand33p on Wednesday August 31, 2022 @02:48AM (#32659165)
>React works great for simple examples and small applications.

I'd like to have some citation here. Most of the product startups use React for their frontend, and they seem to make it work really well. Never saw any issues.

Re:Understanding UseMemo and UseCallback by cageface on Wednesday August 31, 2022 @05:48AM (#32660181)
I'm citing my own experience working on several large high performance react apps. Yes you can make it work. No it's not easy at all.
Re:Understanding UseMemo and UseCallback by acover on Wednesday August 31, 2022 @12:21AM (#32658339)
I converted a long list from Django templates into react. I struggled to convert the code to navigate to a hidden element.

In JavaScript it's document.getElementById and set attribute. In react it's easy to cause part or the entire list to recalculate the virtual dom.

I couldn't think of a good solution. Ideally I'd just call set state on the child element that needs updating but that would require registering all the relevant functions with the parent. Super ugly.

Re:Understanding UseMemo and UseCallback by solardev on Wednesday August 31, 2022 @02:50AM (#32659179)
Can you explain? Are you saying there is a long list, with some hidden elements that need updating (but not rendering)?

If so... can the entire list be stored in state (and updated as necessary), but only the ones marked "is visible" actually get rendered?

Maybe I'm misunderstanding completely...

Re:Understanding UseMemo and UseCallback by acover on Wednesday August 31, 2022 @11:57AM (#32664008)
So in Django templates I'd just flip a style - display from hidden to block of a single div. This would reveal a collapsed section of the tree and I could scroll to the correct div id. (saying list was a bad simplification)

In react because the state flowed from top to bottom I have to be very careful about what objects I update. Just passing down a single reveal could force the virtual dom to update for (num children per node)*depth. Even this required care on what props got updated.

The solutions seemed to be: 1. lots of useMemo so only a minimal amount of a node got recalculated; 2. Directly call a set state function of another child.

Both are quite ugly :( but the second seems nicer as it never could force a full update. However, it seemed to require a registry of set state functions {id: setState}.

Re:Understanding UseMemo and UseCallback by acover on Wednesday August 31, 2022 @12:00AM (#32658238)
Isn't useCallback to solve the common mistake of:

<button onClick={() => setText("clicked")}>click</button>

Without useCallback this would update the dom on every render.

Re:Understanding UseMemo and UseCallback by littlecranky67 on Wednesday August 31, 2022 @03:13AM (#32659293)
Unfortunately the "update on every render" is deeply anchored into devs minds, although in most cases play a minor role. It comes back from a time where browser JS engines where really slow to create lambdas - which is not the case anymore. Additionally, react doesn't really update the DOM on "render" (the internal react render cycle) - due to DOM diffing.

My best advice is (also apart from React): Do not spend time on imagined/anticipated performance bottlenecks; only ever spend time on performance tuning if there are real (perceived, not measurable!) performance issues (there has to be a profiling report in your hand).

Re:Understanding UseMemo and UseCallback by acover on Wednesday August 31, 2022 @12:11PM (#32664269)
Yeah I only started caring about this when tracking down lag in my app. Though it's fun to think about :)

I believe this causes a real Dom update because it can't know the onclick function hasn't materially changed. It's just diffing function references.

Re:Understanding UseMemo and UseCallback by graftak on Wednesday August 31, 2022 @03:50AM (#32659513)
The main use for useCallback is to add a callback to a useEffect dependency array without it running on every render.
Re:Understanding UseMemo and UseCallback by darepublic on Wednesday August 31, 2022 @08:53AM (#32661435)
That's not a mistake lol.
Re:Understanding UseMemo and UseCallback by acover on Wednesday August 31, 2022 @12:04PM (#32664167)
Can you explain why it isn't? I'm probably misunderstanding something.

setText doesn't change because it's from useState. The only reason to update the Dom is because the onclick function isn't memoized.

Updating the Dom every render isn't terrible but it isn't good.

Re:Understanding UseMemo and UseCallback by darepublic on Saturday September 03, 2022 @10:59PM (#32709340)
button is just a small lightweight element usually with a single string child. If passing a lightweight unwrapped click handler to a leaf node is a faux pas then honestly the react team needs to memoize by default. Your description "updating the dom every render..." And acting like indiscriminate useCallback is a panacea for your performance problems to me seems like a pretty naive take. But then again seems like the community opinion in this has shifted, I just honestly don't get it. And I do use useCallback btw, but only when I need to keep referential stability for known reasons,not as an automatic default
Re:Understanding UseMemo and UseCallback by ilrwbwrkhv on Tuesday August 30, 2022 @07:59PM (#32656714)
Just use imba and get much better performance and dx without the pain.