by spankalee · 2y ago · 0 comments
You want to return a description of the DOM, rather than the real DOM, because you want to be able to reevaluate your templates repeatedly with new state, and efficiently update the DOM where that template is rendered to.
All the examples here use imperative DOM APIs to do updates, like with this:
function TodoInput(attrs: { add: (v: string) => void }) {
const input = <input /> as HTMLInputElement;
input.placeholder = 'Add todo item...';
input.onkeydown = (e) => {
if (e.key === 'Enter') {
attrs.add(input.value);
input.value = '';
}
};
return input;
}
class TodoList {
ul = <ul class='todolist' /> as HTMLUListElement;
add(v: string) {
const item = <li>{v}</li> as HTMLLIElement;
item.onclick = () => item.remove();
this.ul.append(item);
}
}
Avoiding those `input.onkeydown = ...` and `this.ul.append(item)` cases, and instead just iterating over items in your template, is probably the main benefit of a VDOM.(The problem with VDOMs is that diffing is slow, a problem solved by using templates that separate static from dynamic parts, like Lit - a library I work on).
In fact I now strongly believe it's counter productive, because most people come to it thinking "I can just trigger however many re-renders of this large piece of UI as I like, the vdom makes it ok" and it doesn't, the performance sucks, but now you have architected the app in a way that requires a rewrite to make the app perform well.
I have seen this exact sequence of events four times, by four different teams. The second, third and fourth, as a principal architect consulting for the team I tried to intervene and advocate for a vanilla architecture that is mindful about performance, citing the issues they would likely experience with react, but to no avail. There was a lot of "oh but there many ways to avoid those issues" followed by a list of things I was presumably ignorant about.
I guess most of us need to learn things the hard way.
Specifically, I'm hoping to show that vanilla architectures can be not only performant, but easy to maintain with well designed code that uses stable and known patterns. Using JSX just so happens to clean up the code nicely and make the relationship between React and vanilla very visible, but that's really all it did here.
Although to be fair, the hack required to get JSX-as-DOM to work is really unfortunately and I'm not very happy with it, and I would prefer JSX to just render as an object tree that anyone can render however they want. But when I tried that for a few months or a year, it was not nearly as performant as rendering them as strings as soon as they're evaluated, which can then be cached via standard module caching. At least, that's how I got immaculatalibrary to entirely render all HTML files in ~700ms initially and ~70ms on most file changes.
I'll try to do some experimentation next week to see if I can get more performance back out of having <foo bar={qux}>child</foo> to render as {foo:{bar:qux, children:[child]}} again though, because that would absolutely be the ideal, and would unfork JSX in the same way Typed Annotations proposes to unfork JavaScript types.
There were two groups I was hoping vanillajsx would resonate with. The first is people who still buy into the React dream but are beginning to be disillusioned with its inability to deliver on its promises, and the second is people who already are fully disillusioned.
I don't know if you've seen it, but Alex Russell just did a blog series where he directly talks about this disillusion and proposes a move away from React for most web apps: https://infrequently.org/series/reckoning/
I am not as anti-React as that myself, but I do agree it is hard to scale up and have it perform well, not at all like the promise. As always, there are no silver bullets and you have to pick a stack that you can understand.
By the way, I made my own pitch for fully vanilla web development here: https://plainvanillaweb.com/
- If the UK GSD is anything like USDS, using them for comparison is like comparing a pro sports team to your local high school’s. They are an outlier specifically created to be better than the average, so tautologically their stuff will be better. Code For America is a similarly odd comparison.
- The US has a massive gap in pay and prestige between public and private sector developer jobs. It’s not that this means “worse” people work at public jobs, but in general they start less experienced and can wind up in a non-learning cycle as they don’t get mentorship/guidance from more expert folks, and if they do get good independently they leave. It’s really hard to convince people to take a pay cut to work these jobs, and many of the few willing to do so instead go to CFA, USDS, etc because they want prestige and avoid all the other inefficiencies in public jobs.
I could go on about the structural problems leading to this, but suffice it to say that blaming React and other JS frameworks is a miss. For some services it’s lucky they are online at all, and a slow web page is still orders of magnitude faster than physical mail or god forbid going to a physical office. The sites could definitely be better but this is not fundamentally a problem of technology choice.
It was attempting to do something along the same lines as you first suggest
Write it in your own vanilla framework, and you will effectively re-invent all the complexity of React, but in a way that no one has ever done before. It's easy at small application scales, but once your app gets large, good luck debugging the thing that exists primarily in your principal engineer's head.
When people say that React is fast, what they mean is that React can dom-diff faster than a naive O(n) approach. It means that updating a component with a thousand nested divs won't crash out your browser, like it might if you were to write the code by hand. It doesn't mean it's an objectively high-performing framework.
What React is good at is forcing you to write code in a clear, comprehensible way. Having every engineer on your team obey F(props) = state is a strict improvement over virtually any other paradigm. (Yes, you can still make a tangle of components if you try hard enough, but the complexity of the tangle is capped significantly lower than the complexity of a tangle of JS without any framework attached.)
Because now everybody know that it's not the case. But if you check the first video announcement from Facebook a decade ago or so, performance was definitely at the front, above everything else.
Separate source of truth from derived data. Separate possibly valid user intent from validated state. Use contexts to organize the data dependency graph of your application. Ensure all your widgets use a consistent value type in and out, don't let events contaminate it. Use something like cursors or optics to simplify mutations and derive setters automatically.
I've never had an easier time building very complex UI functionality than with React. But it requires you to actively start reasoning about change in your code (what doesn't change), and this is something most people are not used to.
Personally I think React compiler is folly for this reason: they are taking the most interesting part of React, the part that lets you write apps that are incremental from top to bottom, and telling you it's too complicated for you to think about. Nonsense.
The issue is just that React makes pros feel like idiots unless they eat some humble pie and grok the principles and the reasons behind it. Which is that React is what you get when you try to come up with a UI architecture that can make entire classes of problems go away.
Without a VDOM, one way data flow, and diffing, your UI won't just be slow, it'll be full of secret O(n^2) cascades, random ifs to stop infinite cycles, random "let's update this state early so other code can immediately use it" ordering issues, and so on.
How many frameworks did you have experience with?
> Without a VDOM, one way data flow, and diffing
you wanted to write "or" not "and", didn't you?
you can adhere to the same principles (one way data flow) without vdom. Not saying it's easy at large scale but it's possible. I don't appreciate people invoking fud towards anyone opting out of their tech choice.
There is a persistent ‘learned helplessness’ tendency among some developers to assume that the frameworks they are using have access to magical mystical powers above and beyond those that their own code can make use of.
Framework code might well be better optimized or more tuned than the code you would write - but if you cared to employ similar techniques you could achieve those same gains; on the other hand, since by definition it’s more flexible than single-purpose code, it might not be optimal for your usecase.
A rewrite on those occasions, I do not consider possible. Most businesses are way to deep into frameworks.
What I personally advocate is to choose frameworks with valid escape hatches, and then make sure to staff a team with JavaScript programmers rather than some-framework Andies.
In an even larger scale, I advocate for web-component based solutions. I try to stay close to vanilla as much as I can. Whether I like it or not, it's the highest value professional decision, imo.
As far as I understand, signals make it much easier to keep the DOM updates to a minimum.
More concisely: JSX is just an alternate function call syntax with some useful applications.
For example at my last company we used JSX to make test data factories that had an XML-like look but were using a builder-pattern in the element creation that was able to make contextual decisions about what was in the final data. Nothing to do with React, DOM, or inability to express the same thing declaratively without JSX.
Thats really interesting, can you elaborate more?
For example did you use a specific JSX compiler? Was that written in house or used a 3rd party library?
Depends who "you" are. I prefer to have my DOM nodes updated in place without all the reconciliation machinery. (no implication about what you want)
I was painfully reminded of that while visiting Europe last month on a data plan which was clearly deprioritized on partner networks - the old sites with .php in the URLs loaded in a few seconds and worked perfectly, but every time something failed to load in less than 5 minutes or partially loaded but didn’t work a quick trip over to webpagetest.org showed a lot of NextJS, React, et al. scripts trickling in because clearly a form with half a dozen fields needs 25MB of JavaScript.
The root cause is obvious: you get what you measure. If businesses prioritize Jira tickets closed per day, they’re going to get this soup of things promising to be easy to use for high developer velocity and they’re never going to get around to the optimizing it. If they’re trying to be able to hire as cheaply as possible, they’re going to look for the current tool boot camps are pushing and hire based on that, not looking for deeper knowledge of web standards or experience which costs more and shrink the candidate pool. If they’re looking for a safe choice, Facebook’s marketing means all of the big consulting companies will push React and few people will pause long enough to ask whether they’re building the same kind of apps it was designed to build (long session times, tons of local state being mutated, etc.) or whether they’re willing to invest the time needed to get it to perform reliably and well.
In all these frameworks, mutations happen inside effects, and effects are scheduled such that they all happen at the end of the tick, avoiding reflows and thrashing.
If all JSX does is return a DocumentFragment that you then need to imperatively add event listeners to and imperatively update, how is it much better than innerHTML?
This in theory could do something to copy that local state over, or diff the two DOMs directly without a VDOM (though from the sound of it, it probably doesn't).
You can have imperative event listeners and updates.
These are two independent dimensions. I made UI framework called mutraction that produces real DOM elements from JSX expressions. It also updates any contents or attributes of those DOM nodes based on their dependencies without requiring imperative DOM interaction from application code.
https://github.com/tomtheisen/mutraction
Here's a click counter. `track()`, as you might guess creates a proxy so that reads and writes can be converted into dependencies.
const model = track({ clicks: 0});
const app = (
<button onclick={() => ++model.clicks }>
{ model.clicks } clicks
</button>
);
document.body.append(app);2) Autocomplete for element props.
3) IDE support such as refactors and jump to definition/jump to usages.
4) Proper syntax highlighting out of the box instead of the editor just saying "there's a string here".
5) A uniform pattern for defining custom components that work the same as primitives, rather than defining custom components as helper functions returning string fragments or something like that.
And so on. JSX has a lot going for it regardless of the semantics chosen. It's just a syntax that is very convenient for lots of kinds of tooling, and it's completely unopinated about the semantic context in which it is used.
I get the "no more imperative updates" dream. I've used these frameworks for probably a decade. I've mastered them.
Me personally, I prefer imperatively updating my DOM. I get completely fine-grained control over what's happening. I can architect it to be an extremely efficient machine. I can make it extremely easy to add/change/remove/fix features in my apps without forcing myself to think according to anyone else's opinionated methodology.
The farther you get into complex GUI territory, the more you want a declarative, functional approach, because it makes things simpler. The closer you are to a handful of controls with simple logic, the more you want to just imperatively tell them what to do, and leave the rest of the page alone, because it makes things simpler. We now just have better tools than jQuery for that.
I feel like this is one of the leakiest abstractions in all of computing. There's a reason there's an entire cottage industry around react; how to stop things rendering multiple times, refreshing needlessly, etc.
[0] https://blog.metaobject.com/2018/12/uis-are-not-pure-functio...
>you want to be able to reevaluate your templates repeatedly with new state
No you don't. It is inefficient and increases complexity. You then have to extract and keep track of state yourself where the platform/UI components could have done much of this themselves.
Calling the same method over and over again is wasteful.
So we don't do that.
First, we did not start with the obviously incorrect premise that the UI is a simple "pure" function of the model. Except for games, UIs are actually very stable, more stable than the model. You have chrome, viewers, tools etc. What is a (somewhat) pure mapping from the model is the data that is displayed in the UI, but not the entire UI.
So if we don't make the incorrect assumption that UIs are unstable (pure functions of model), then we don't have to expend additional and fragile effort to re-create that necessary stability.*List reconciliation still has to happen, but you don't need to pull out an entire vdom. You just have to have some mapping between list items and their resulting DOM nodes.
This mind numbing reliance upon layers of abstraction nonsense around state management is why I really don't like React. State management is ridiculously simple. State management, when done correctly, is the most primitive example of MVC with no abstractions needed.
You might be able to handle this while you're alone and you know everything about your codebase, but the moment you're working with someone else or in a team this will no longer be the case.
As the user, not you the author of some code, make changes to the UI it will be via events. In the respective event handlers just update a big state object with the identity of the node and how it is changed. When the page loads simply read from that state object to recreate the respective node exactly how they were when the user modified them. That's it. Nothing more.
Its how I wrote a full OS gui for the browser. It does far more than SPA framework, does it substantially faster, and requires only a tiny fraction of the code.
Yes, yes, here come all the excuses, like: I can't code or it wont work in a team, because other people cant code. Stop with the foolishness. Provide some governance, preferably fully automated, around event handling and you have complete obsoleted your giant nightmare framework.
I describe it here: https://github.com/prettydiff/wisdom/blob/master/state_manag...
It's also not even an either-or. I've worked on a codebase that did both: React was loaded for some views & others were served with a lightweight JSX renderer.
I wanted to add my two pennies to the discussion. You are of correct that with that approach you lose the declarativeness but sometimes you don't need that, if the thing is mostly static.
I went this road many years ago for a project. The nice thing of this approach is getting rid of all the ugly DOM API but enjoying it's performance over innerHTML.
(1) I absolutely love lit-html but don't like the rest of the lit components framework. Luckily you can use it independently!
It works great! I was amazed at how you can do so much in templates, it's pretty much everything I could do in Vue templates, though a little more verbose.
I built my own `VanillaComponent` class, which has a mount() method which calls the render() function which I define on the child class.
My VanillaComponent class looks like this:
import { html, render } from "lit-html";
abstract class VanillaComponent {
abstract render(): ReturnType<typeof html>;
private _mountPoint?: HTMLElement;
mount(this: VanillaComponent, target: HTMLElement) {
target.textContent = '';
this._mountPoint = target;
this._update();
}
_update() {
let templateResult = this.render();
let rootPart = render(templateResult, this._mountPoint!);
}
}
So I can write something like class MyComponent extends VanillaComponent {
constructor(props: { label: string }) {
this._props = props;
}
render() {
return html`<button>${this._props.foo}</button>`;
}
}
Then I can instance like so: let myComponent = new MyComponent({ label: "I am a button" });
let target = document.querySelector("#demo");
myComponent.mount(target);
The base class stores the root node (target), so later I can do myComponent.update()
to re-render, taking advantage of lit-html's "diffing" logic.However something I have not been able to solve with lit-html only, is when I compose parent and child components I have to do something like :
class MyDialog extends VanillaComponent {
render() {
let childComponent ... // another VanillaComponent previously instanced
return html`
<div>
${childComponent.render()}
</div>
So the child component I need to explicitly call render() to get the TemplateResult for the parent template.But this means I can not do `childComponent.update()` because I don't know the root element of child component, since I did not mount it explicitly myself.
I mean technically because of the lit-html optimizations, I can do `.update()` on myDialog (the parent component) after any child component's props changes, and it will only re-render what is necessary... but let's say my child component has like 1000 cards... it seems very wasteful and it would be ideal if I could re-render only the child.
I wonder if there is a trick to get around that with just lit-html?
I think in this case the ref() directive - i.e. https://lit.dev/docs/templates/directives/#ref - may be what you want. If it isn't exactly, reading how it's implemented would be my first step towards building something similar that is.