Hacker News new | ask | show | jobs
by kareemsabri 1399 days ago
Yeah, this is not to belittle the complexity of React under the hood. But they are functions, and it seems you can assume they will be called in a straightforward manner when they render (whether they are invoked as explicit function calls or via returned JSX).

The only real complexity (for the developer) is the use of hooks, effects etc. if you don't mess with useMemo (which you generally shouldn't). Certainly they aren't pure functions, they have side effects and are stateful, and that has some nuances, but (kudos to the React team) once you understand hooks as a reference to the instance value and a setter for that value, they're pretty easy to understand.

I guess I don't personally find thinking of them as a class as that useful, my mental model of "it's just a function with some external references (via hooks)" gets me there.

1 comments

> if you don't mess with useMemo (which you generally shouldn't)

why? is this not the primary way to re-init expensive internal component state when specific props change?

GP's claim is a little too strong, but in my experience most uses of `useMemo` / `useCallback` are only necessary because people define things in the wrong scope, or write giant spaghetti components with 15 different props and no internal structure. The best memoization technique is not calling things repeatedly in the first place.
I find it necessary for a lot of different types of patterns that optimize performance. See the very recently written beta react docs, they go over this quite well.

In general, I think it's always a mistake to tell people "don't use this tool because you may shoot yourself in the foot", best to explain the when and why. But I do have a problem when the tool has just stupid defaults that make it harder to use correctly in the first place.

He touches on this in the piece briefly.

> I think as developers, we tend to overestimate how expensive re-renders are. In the case of our Decoration component, re-renders are lightning quick.

Certainly it's there for a reason, and you may have expensive operations, but in my experience developers reach for useMemo much too early and often, and it just adds complexity to their functions. The cost of checking the parameters for changes adds overhead that may be more expensive than just re-doing the "expensive" operation. My rule of thumb is if the operation is less than O(n) where n < ~5000 I don't reach for useMemo.

There have been some benchmarks done on this, and when it pays off to use.