by andrewmcwatters · 3y ago · 0 comments
I'm disappointed by the fanatical adoption of hooks, but I saw it coming and I can't say their legacy documentation didn't warn me.
I'm happy that other people seem to enjoy them without restraint, but obscuring magical details and making side effects seem like more of a big deal than they really are in programming seems like a design choice intended to infantilize engineers and shelter them from reality.
I might finally invest some time into what it looks like to create front ends independent of any of the existing frameworks that exist today, which I think is probably controversial, but I want the decisions I make to last longer than the whimsy of engineering teams who don't care that they might change their mind in 10 years.
I think having seen front-end software come and go so many times, I'd rather write some simple utility functions wrapping `Document.createElement()` and use native event handling.
Too much fluff in front-end.
I want the decisions I make to last decades, not just a few years. I don't think that's a sentiment appreciated by most, though.
It's a joy to work in, feels "frameworky" but it's just web standards with <100 lines of convenience JS wrapped around it. There is no magic beyond what the browser provides - I like it that way.
https://github.com/retrohacker/template/
It's "open source" as a reference. Just using it for myself. There aren't many docs beyond notes to myself. But the actual framework is a 90LoC JavaScript file that is an easy read.
You're welcome to kick the tires. If you like it I'd entertain PRs and stuff but it's such a small library forking is probably entirely reasonable to make your own flavor too.
The general idea is you extend the Template base class and call "super" with the id of the <template> that will get bound to the ShadowDOM when the class is mounted. Then you call instance.mount and pass a dom node to mount it into the DOM. For child nodes, you use `this.fragment.querySelector` to select them from the <template> you mounted. It supports garbage collection by tracking children, so when you "unmount" it recursively unmounts all child instances as well. Finally it has an event emitter implementation, so changes/actions/events bubble up the DOM while state can push down through the DOM. Keeps things clean.
I recently added state methods since I was duplicating state management everywhere. Now the base template class has a `setState` that will emit a single `change` event for all changes in the current "tick" of the browser eval loop.
Cheers and happy hacking!
But I do agree with the CLI for bootstrapping being a problem for react. It's less of the CLI itself and more of the mountains it moves under the hood to setup the app. I run a single command and get an absolutely massive project. Yes the final dist file is only KBs in size, but the entire build process that gets scaffolded is still part of my project. That single command install seems "easy" but leaves me with a huge amount of existential dread - no matter how much the tooling "paves the path" it doesn't delegate responsibility. Ultimately I'm on the hook for this application and when things don't work it's on me to understand why and fix them. After a CRA install, I'm often left feeling like I'm looking off a cliff into an abyss that is going to take a huge investment to understand.
The last time I used React was inside a big company. I felt safe using it there because there was a team responsible for "owning" react inside the company. I followed their docs to start with CRA and pull in their component library. If anything inside my CRA app went sideways I _had_ delegated responsibility to another team for that, I had a support line that I could reach out to to get help and ultimately problems at that level were their responsibility. That isn't true in my personal projects - so I don't use it there.
FWIW I actually feel the same way about infrastructure components. I am Terraform certified, have been sysadmining Linux installs for over a decade, have built a serverless platform inside FAANG, played SRE, etc. But still K8S, Linux, etc. leave me with similar feelings. When I can delegate their responsibility I'll build on top of them or participate on teams that manage them, but for my own stuff there is too much to chew for me to adopt that for a personal or client project. Even with my background, for my projects I choose platforms where I can delegate that part of the stack to a vendor. These days I'm building on Cloudflare Workers, R2, and PlanetScale for my DB (until D1 is prod ready). When I adopt a service - I pay for it at a rate that gets me support contracts. That $$$ is funding an engineering team far greater than me to build, support, maintain, and understand that chunk of the system so I don't have to.
I will never forget the visceral disgust I felt in that moment.
I just put together a content style website using nothing but web components and used a base class to put my global styles into and just inherited my various components from it.
Was also really easy to factor out shareable styles like various page layouts using a similar technique.
That just left me with doing small targeted tweaks where I would override things with custom properties along the way as needed plus any component specific styles.
Was probably the cleanest approach I’ve had in as long as I could remember. Plus it was delivering me a perfect 100 score in Lighthouse too for what it’s worth. Would recommend.
If you make changes, I'd appreciate a follow up GitHub comment that lets me know where you made improvements, but no obligation. It's licensed under a BSD-style license so you're free to do with it whatever you like!
Edit: Hey another Arizona hacker! Right on!
Just checked out your website. I'm also doing Software consulting in Arizona, would love to grab coffee (digital or otherwise) and compare notes.
If you are in the PHX area, checkout https://www.heatsynclabs.org/ - they do Coffee & Code every Wednesday.
I’ve used React and Storybook quite a bit - this was inspired by those experiences. Haven’t used Backbone in over a decade.
The writing has been on the wall for 4 years that hooks are the future. You _can still_ use class components. Function component with hooks is the simplest API you can get to React itself—classes are more of an abstraction.
> I'm disappointed by the fanatical adoption of hooks, but I saw it coming and I can't say their legacy documentation didn't warn me.
We all adopted hooks because it makes things easier to reason about. If you’re still having trouble understanding them, I’d urge you to dig deeper into how they and React works.
> I might finally invest some time into what it looks like to create front ends independent of any of the existing frameworks that exist today, which I think is probably controversial, but I want the decisions I make to last longer than the whimsy of engineering teams who don't care that they might change their mind in 10 years.
I can’t think of a better way to develop an appreciation of UI frameworks that to go without.
> I want the decisions I make to last decades, not just a few years. I don't think that's a sentiment appreciated by most, though.
Barely any software runs untouched for decades (documents don’t count). So it’s not that the sentiment isn’t appreciated, I think most of us would agree—it’s that it’s an impractical expectation.
Plenty of software runs untouched for decades. A lot of it powers your interactions with people on HN right now, from drivers, to font rasterization and backing layer UI composition. There are bugs in codebases that have taken 20 years for people to even notice. It happens.
When people don't have to worry about trivial details, they can focus greater efforts.
Railing against it is railing against the best-in-class example of what you want... even if it still falls short of what you want. A decade is nothing to sneeze at.
We've had React 1 (components) and now React 2 (hooks), they just managed the transition better than angular and so gobbled that market share.
jQuery stayed mostly stable, there was only one version that I can remember where it was a bit of a hassle to upgrade it. But it's quite a while ago now, so could be mis-remembering.
React has more staying power than almost any other JS library I’ve seen. And they’ve maintained backwards compatibility on par with Windows.
The other day dang was mentioning how HN struggling under the popularity of the GPT4 thread[0]. But even then, surely HN has seen some code updates. If you look at HN as a product (and not a codebase), the unofficial/official algolia search engine is an addition.
What runs untouched for decades?
Typically written by folks who aren't even aware of the problems they are trying to solve, no tests, and event and timer leaks.
Winamp? Check.
Spacemonger? Check.
FLAC encoder? MP3 encoder? Notepad++? Savihost? TheGodfather? Flash Player? MS XML Notepad? ConEmu? Some really old build of CockroachDB? CPU-Z? Doom Builder 2? HexChat? Hell, even mIRC? Check check check check check checkity check.
None of those have been updated in years, many untouched (but not unused) since the day I installed them. This is why the web is so effing stupid. (And a hat tip towards Microsoft for keeping promises, unlike web developers)
And in many cases they STILL work better than the crappy little my-first-webapps that everyone uses instead nowadays.
Software is and should be eternal. It's these damn platforms that nobody wants to hold still with.
They could have stopped changing React. And people would have moved on to other things.
God I wish!
Also custom hooks are vastly more readable IMHO than HOCs.
> Why do you need this?
> Why can't I just update the ref however I want!
Look up forwardRef:
> Why can't I just access ref as a prop?
Further, everyone is trying to cram all logic into hooks and components. It's to the point of insanity. Look, React is so popular I know most are using it for throw away marketing sites and other low-tier shit (sorry y'all but you know it) but.. This architecture doesn't fly in large apps; ee b2b etc.
React Router v6 seems to have no non-hook based APIs that aren't marked private!? They screwed the pooch on useNavigation; it causes unnecessary re-renders. Surprise surprise, but if they can't get it right...
Whoa, you lost me here. React Router is no shining beacon of good API design. They've never done things well, just "well enough". I'm not saying RR is terrible, I'm not saying the RR devs should feel bad about how bad they are or something, I'm just saying that these guys are not the guys you want to point at for "if they can't get it right...".
(Example of RR being not-so-amazing: Initially (v1? v2?) they required you to use attributes for the components that would render in a route, with no way to specify props short of making a custom component that wrapped the one you wanted. Then they added the ability to pass a function as an attribute, which let you specify props, so that was usable but clunky. Then, in yet a third version of the API (I think this is by v4?), we got the ability to use JSX in children to fully specify the components, which obviously was the right choice all along, it's literally the point of JSX. And again, I'm not saying I'm a better software engineer than those guys; I think I'd have got this one right but I'm sure I'd have screwed up a dozen other things.)
* It is the de facto "official" community router solution
* It's made by the same team as Remix..
I think it's more charitable to assume that the designers are designing this for themselves and are just being aware of their own fallibility and limited mental capacity (we're only human after all), not seeking to infantilize or shelter some lesser class of programmers.
You seem to be taking it too personal. There's no need to call others infants for preferring hooks.
Asking for an API interface to be stable for decades __across all future versions of the library__ doesn't sound realistic to me. Nothing is forcing you to update to the future new version of react - which has not been released, and is likely years away - that removes support for class components.
So they're still not breaking backward compatibility. Looks like you don't have to refactor until you need something that's only hooks based.
I didn’t want to adopt functional, but let everyone make their own decisions on what to use, and now I’m very happy I did.
Oh right, you meant React wise... yeah...
Clojure and ClojureScript very much appreciate that sentiment. re-frame, a library for creating React apps with ClojureScript is rock solid, many years old, and still on version 1, meaning no breaking changes so far. 5 years old re-frame code still looks the same today.
Now that class components are essentially deprecated in the documentation, and the fact that React 18 support is still an experimental feature in Reagent, people using ClojureScript and React today are in quite some trouble, especially since React is the only JS framework I know of that is compatible with functional programming.
While reagent is able to emit function components, there is a performance penalty to this, since it employs some hacks in order to be compatible with both hooks and ratoms. Thankfully there are some projects that are attempting to bring modern React[1] and even bring the whole re-frame API alongside it.[2]
Last weekend I decided to try out helix, refx, reitit, and shadow-cljs' lazy-loaded modules and managed to make a pretty nice demo app that uses essentially the re-frame API but it's all modern React and hooks, and the router was capable of lazily loading modules containing code of pages the user wanted to navigate to.
I addressed this already: while reagent is able to emit function components, there is a performance penalty to this.[1]
> I also very much like Hiccup, and so do many of us, because code is data and data is code, and Helix has decided not to support that.
Hiccup is convenient to write, but it is a constant run-time cost and a significant storage cost given that you have to store long series of constructors to cljs.core.PersistentVector in your bundle, have the JS runtime actually construct the vector, then pass it through a Hiccup interpreter to finally produce DOM nodes and throw away the persistent vector, only to repeat this entire process again on re-render.[2]
> Helix has decided not to support that.
That is simply not true. From the Helix documentation: "If you want to use libraries like sablono, hicada or even hx hiccup parser, you can easily add that by creating a custom macro"[2]. These are all Hiccup interpreters you can readily use. IME there is very little difference between using the $ macro in Helix and writing Hiccup. I do not really miss Hiccup when I use Helix, and you still have data as code, the data is in a macro but that macro itself returns data...as code! ;)
While this is from an unrelated project, there are benchmarks[3] done against Reagent that demonstrate the sheer overhead it has. In practice it is not a big problem if you rarely trigger a re-render, but otherwise it is a non-trivial cost, and if you want to use modern React features (like Suspense), there is a lot of r/as-element mingling going on, converting cases, etc. that simply make Reagent feel more tedious to use than Helix.
Also, the newer UIx2, which largely borrows from Helix, is "3.2x faster than Reagent" according to one of the contributors.[4]
I think it'd be worthwhile to benchmark all of these libraries against each other and record the data in one place. Maybe I'll get around to doing it this weekend :)
---
[1] https://github.com/reagent-project/reagent/blob/master/doc/R...
[2] https://github.com/lilactown/helix/blob/master/docs/faq.md#w...
There are many valid complaints to make about React hooks, but I'm not really seeing those here. And I'm not seeing evidence that you've crossed chesterton's fence with them either.
I'll criticize hooks all day, but for all their footguns, they provide a level of abstraction (and a simplicity of implementation for it) that's really hard to argue with. They let you break up reactive stateful code in maybe the most scalable way I've ever seen, and their contract with the outside world allows for some crazy optimizations on the framework's part. I think the team is onto something really special here
Of course they're also easy to misuse, and they can be really "magical" until you fully grasp them. Those are problems the ecosystem will have to grapple with (and I know the core team is aware of them). Though the "magic" at least is due more to weirdness and inversion of control than it is to actual complexity. Having a grasp on how they work, I feel like I wouldn't have too much trouble implementing a basic version of the same system myself, because the primitives are ultimately not very complicated
I believe hooks are really good bones for building UIs, and I think they'll last because of it, even though the surface developer experience has some warts for now
React Hooks, if anything should have just been called React Callback Queues.
As for emotionally charged words, maybe it's not appropriate in the current zeitgeist to post without some degree first of self-censorship, but it's how I feel, so I'm going to say it.
React Hooks were fanatically adopted, in my opinion. Side effects are a regular part of programming. I find it, thusly, infantilizing to hide those details.
I wish people would stop this sort of thing, but if you want to say your part and that's how you feel, say it too.
Edit: You've apparently even been downvoted for expressing this sentiment, which I hate on HN, because it's how you felt. I wish social sites wouldn't do this. No one should be able to invalidate that.
It was one of those things where the ecosystem had to be unified, because a fractured ecosystem would have died. The React team said "this is the way we're going", and people followed along not because they were fanatical, but because that's the path that was set out. We can debate whether hooks were the right call for the core team to make, but I think it's incredibly uncharitable to say every library author who went along with it was just being "fanatical"
> I find it, thusly, infantilizing to hide those details
Software development is all about hiding details. The key is picking the right details to hide and not hide. Hiding details (ideally) lets users focus on the parts that matter to them, and gives the compiler/framework/system room to optimize the rest.
In React's case, we got features like automatic batching (https://react.dev/blog/2022/03/29/react-v18#new-feature-auto...) and concurrent mode (https://react.dev/blog/2022/03/29/react-v18#what-is-concurre...) for free, without having to modify application code, because the application code was already abstracted enough that the framework could significantly change how it did things behind the scenes without changing the contract
In terms of developer experience: I consider myself to have a fairly deep understanding of the browser platform, and a fairly-complete understanding of how hooks "really" work, and I'm still glad that I have React's abstraction layer most of the time when doing real work at my job. There are escape-hatches, as there should be, and the rest of the time I'm really very happy not to have to fiddle with all the bits when I just want to render another form and implement some business logic. I don't feel the least bit infantilized.
There are things I don't love about hooks - mainly that they do things which should really be language-level features, and that causes some dissonance - but here's what I love about them:
They expose a tiny set of primitives - pretty much just useState and useEffect (useMemo, useCallback, and useRef can be implemented in terms of these!) - which plug directly into the simplest, smallest side-effect-y things we need to be able to ask the React framework to do for us. And then, because these state and side-effects primitives have their own reactivity baked in, we can compose them into larger stateful/side-effect-y abstractions which also have their own reactivity baked-in (unlike classes, unless those classes are full React components). We can build amazingly high-level, convenient abstractions on top of this amazingly minimal set of reactive primitives, which will always themselves be reactive, no matter what. And then the framework can break them back down into the primitives at runtime (in fact, it never sees anything but the primitives), and schedule and re-order and do all kinds of nifty stuff with them without breaking contract, because the contract is tiny and elegant.
In my experience that's unique and beautiful.
It's truly amazing how React team manages to present leaky abstractions as something that community should celebrate. Or maybe what's amazing is that community is gullible enough to buy that. That's exactly the fanaticism your opponent is talking about.
Batching isn't a new feature (it's also not a React-specific feature). Looks like batching became more fragile with hooks, so they had to fix it later.
But of course React team doesn't call it a bugfix. Meet a new feature: "Automated Batching". Great marketing.
It seems like you're saying that benefit of hooks is that they made it possible to solve problems caused by hooks.
Which actually rings true: I found that React folks absolutely love solving problems, and they love React precisely because it provides a never ending source of solvable engineering problems.
Of course, since your engineers will always be busy with engineering problems, they will have very little time for product problems. So your product will suffer, but at least your engineers will be happy. They get to talk about so many cool things: immutability, hooks, batching, concurrency, memoization (ironically, the opposite of hiding the details). Given how expensive engineers are, it might be a fine tradeoff for some companies, though I personally would never want to work in those.
Also, after taking a quick look at Dan's post on batching, it seems like their solution is a great example of leaky abstraction. Their intention was to batch rendering, but they implemented it by batching state updates. Which means you can't expect to read the new state right after you set it. As far as I remember, both Vue and Svelte also implement batching, but they don't suffer from such counterintuitive behaviors.
With the WebComponents movement though, we are getting ever closer to being able to rely on native browser functionality for a good share of what frameworks set out to do. We're not all the way to bliss without frameworks, but for what it's worth here is my 481-byte library to support template interpolation with event binding in order to make WebComponents pretty workable mostly as-is: https://github.com/dchester/yhtml
It's a low likelihood, but I'd rather stay up to date when I can.
Do it. Don't be afraid to, either.
Over the years, I've put together a list of some big and VERY big companies whose web developers hand-code their web sites without assistance from the framework-du-jour.
I recently learned about a new one for my list: A nine-figure household name tech company.
The list is useful for when I'm in bars or developer meetups or coffee shops and someone who's only been putting together web sites for a few years starts preaching about how whatever shiny new thing they just learned about in junior college is the one and only way to do things.
Not sure controversial is the right word, in fact I think it is quite a common sentiment among developers, especially those that originally come from back-end. The only problem is finding a company that is willing to forgo the frameworks.
They do exist though. Here's a short list of companies that use vanilla JavaScript, most notably GitHub and Netflix:
You can’t even just keep using class based as they have no way to consume hooks.
Unit testing of hook based code is non existent IME. It’s some kinda funky E2E feeling test.
React was my favorite framework before. It’s really a shame.
I’m guessing you’re referring to the fact that you can’t access component state like you can with class components. If so, that’s not required to do a unit test. That’s a sign that implementation details are leaking into your tests.
The entire front-end framework landscape is like this. It's all designed to appeal to the kind of "engineer" that just wants to copy paste code and have it work like magic without ever thinking about what's actually going on.
I think there are two approaches to software development, and a gradient of people transitioning between them:
(1) I’m responsible for this system and I either have to understand this well enough to feel comfortable being directly responsible for it or delegate responsibility through my org structure or vendor contracts.
(2) I don’t understand how any of this works, it’s just a bunch of magical incantations that get me results, and one incantation is interchangeable with another.
Your dumbdumb fake engineer isn’t a fair characterization of (2) but I do believe a lot of tools in a lot of ecosystems are optimized for engineers without the depth of knowledge necessary to operate them under the API contract.
That’s totally fine when that API contract is provided by a responsible party you can delegate responsibility to. The problem comes in when you provide these “simple” API contracts on top of extremely complex internals and hand them to a developer/user who is ultimately responsible for the entire stack, internals and all.
In some cases (2) can offset risk using a “cattle” approach where multiple live versions of the system are kept up, changes happen one at a time, and you can fail over if something goes wrong and throw away the old state. I’ve met engineers who operate K8S clusters this way. They are clearly out of their depth with kubernetes, but they can fail over to a secondary and rebootstrap a bad cluster from scratch to get back to a good state. By keeping things disposable you exclude most (all?) failure modes other than “poison pill” bugs that repeatedly put your system into a bad state.
But, for the most part, these complex open source systems that try to hide complex internals give the illusion of delegating responsibility. You might get pretty far before an incident comes knocking and it’s time to pay the toll.
That's why I look down upon engineers with your mindset. I won't generalize all backend engineers as you did to frontend though.
I've met many who get it but of course prefer the peacefulness of controlling the execution environment and the limited state of a server.
Btw imo backend is boring because the reasons above, frontend has a lot more going on. As a full stack engineer I'd say frontend is much much harder, and that's why you have all the tech trying to make it easier to scale and maintain. That's not to say backend doesn't have it's own difficulties. It all depends what you are making too. A website is easy, a complex app is much more difficult.
Every engineer I’ve known who’s “looked down” on frontend or was dismissive of it was not only bad at frontend and didn’t understand what it takes to be good at it, but also a jerk about the perceived depth of their own knowledge.
It sucks that people learn this the hard way, though, and the only way to grow beyond this for people new to the field is to eventually get burned and learn there are other ways to do all of this.
There are whole generations who don't know what session cookies are! And... that's just OK.
I really enjoy JWTs, but the idea of sending all my user data on every request hadn’t occurred to me, and still feels mildly wasteful.
You could utilize a key system to gain the same advantage as not having to use persistence as one gets using JWTs when implementing session cookies, if you wanted, too.
My biggest gripe with them as a technology is that they have no way to associate a `<style>` tag in `<head>` with a ShadowDOM tree (short of cloning and injecting w/ JS).
The only way to say "this CSS goes with this <template>" is to nest the `<style>` tag in `<template>` itself or painstakingly expose `part`s on everything you want to style.
I'd really like a template selector for CSS where I can say something like `::template(#id) button` to select all buttons inside the `<template id="id">` for whatever ShadowDOM it is mounted to.
Without this, I either have to do CSS in JS, CSS in HTML, or I have to use special build magic to take my standard index.css files and inject them into my HTML or JS. All of that is kinda gross.
If you want to support your case, you either inject css or you design your web components to support css variables which pierce throgh the shadow dom.
Let’s better spend time on important things instead of wasting time trying to make UI behave properly across a plethora of browsers, OSes and platforms.
Cross-browser compatibility was the problem that jquery was trying to solve back in 2008 or thereabouts. Not a problem that react is trying to solve in 2023.
It seems they are getting bored.
I'm running two businesses with a third on the way. I have bigger problems than people reinventing stuff with no benefits compared to what we were doing 20 years ago.
I'm writing software every day, so I'm still involved in front-line work, but I'm interested in being the level of productive most people aren't.
So the bigger questions on my mind are things like, "What knowledge can I build up that doesn't become obsolete?" "What social effects drive adoption that endanger those goals?"
Those are questions that have, at least immediately, very little to do with implementation details, and are questions that help me navigate whether to ignore new technologies all together, or when I identify something new when I decide to adopt it.
A part of that is looking for cues from maintainers that say, "Hey, we care that you're shipping, and we're not going to endanger your labor spent learning our intellectual property."
There are things that you complain when you are junior, but start to understand better and realize why people do certain things in a certain way when you get more experience and can look at things from a higher viewpoint.
I'm not a frontend dev by all means, but I must say, I've worked on such projects (100LOC create utils & event handling) and it was a joy. I always wanted to recommend it to people when they complain about the state of js frameworks, but I felt I've no authority to do so, because my experience is limited (only internal projects).
New to frontend?
This is a great idea. Nothing controversial about it.
Lots of engineers out there today who don't have a simple answer for, "So what happens when one of your dependencies no longer exists on the Internet for one reason or another?"
For this to be a problem would require it to disappear from both npm and Github simultaneously, and for none of our devs to still have it on their local machine so we can reupload it under a different name.
Like, I didn’t think about that until you wrote it, but coming up with an answer isn’t exactly hard.
I’d rather worry about things that are more likely to happen, like someone accidentally dropping the prod database tomorrow.
And when you're a prolific writer and you've experienced more than just npm and GitHub, you're going to run across a scenario that makes you start thinking about how your practices in one ecosystem don't apply everywhere.
I own intellectual property composed of dependencies that can't be obtained anymore. Or two people in the world are the only individuals who are known to still have the dependency, but neither of them will supply it.
What's your plan for depending on a SaaS who goes out of business? Is everyone experiencing that on a regular basis? No, they aren't. But then you do. Once. And it changes how you do everything later, because you no longer have the privilege of not thinking about it.
Can I rephrase it to something more realistic?
"So, what happens when one of your dependencies is no longer maintained, for one reason or another?"
or
"So, what happens when one of your dependencies conflicts with a newer version of another one of your dependencies, which you are keen to update for one reason or another?"
I’m by no means in the web-development-sucks-lets-kill-the-build camp, I think modern web frameworks and tooling can be incredibly useful particularly at scale (people, codebase, features), but JS dependency management is pretty nightmarish rn.