As someone who doesn’t use React day to day but dips my toes into other people’s projects, this kind of thing really leaves a sour taste in my mouth. I get that it’s a stripped down example, but even stripped down, it’s too much boilerplate. The equivalent code in Vue 3 is a trivial reactive object, but beyond the ugliness of hooks, why are you passing around state in such a complicated way? Vue tends to work with “props down, events up”. If your inner component needs to be able to issue state changes, it can just bubble up an event and let the outer component catch it. Or you can just send a raw reactive object and trust the sub-component to use it responsibly. React is both more code, less opinionated, and less flexible! It’s remarkable to be bad at all three.
Yeah - I know useState(), but I had to go and lookup both React.useCallback() and React.useMemo().
This does look to me like the kind of pattern that should be used sparingly, else your codebase may end up spending more time applying “better” patterns than it does actually implementing your key features. I’ve seen that happen before, it’s not pretty!
Part of me wonders if perversely React is coasting on the benefits of the sunk cost fallacy: “Well, it took so long for me to learn the difference between useCallback and useMemo and choose a style for when I use what, why would I go to all the trouble of learning some other JS framework?…”
To me, it seems like the benefit of React is there is a big ecosystem of existing components. But in basically every other way you’re better off with at least using Preact if not something easier to use like Vue or smaller like Alpine or more logical like Crank and Solid… It’s becoming the WordPress of the frontend.
You’re right to think so. I do do react every day, have done for years now, and this is just the tip of the iceberg of unreadable obfuscation created by hooks. Hooks are great for 20-line components with 2 or 3 stateful properties, or when you just need a throwaway example for storybooks or something, but they’re a net loss. It might be possible to use hooks in larger components and across entire sites without making everything abstruse and harder to reason about, but I’ve never seen anybody manage it.
It’s a good article. The one thing that bugs me is the use of useCallback when it’s not necessary (in the first example, where none of the setter functions are getting passed on to children).
Memoization always comes with a cost.
This basically boils down to good programming and clarifying interface boundaries. Prefer naming things over sprinkling anonymous functions around. The react hooks used in the examples provide no benefit and actually slow the code down.