99 points · by gdad-s-river · 5y ago · 168 comments
Just put the checkbox html & css on the page. Write a function that updates the label based on checked state. Call it on input/change events.
It's like 3 lines of js.
React.js people always invent this vanilla js / jQuery strawman that's so complicated and spaghetti that no mortal can possibly understand it.
It's total BS. You can write succinct maintainable code without a 100 lb framework.
The vanilla code was much easier to maintain too. React comes in your way when things get complicated and the work arounds produce really messy code.
Edit:
Project (GitHub): https://github.com/labmlai/labml/tree/master/app
It's a mobile/web app to monitor machine learning experiment.
It's not the final say. Just a strong signal among many others.
Also there is nobody stopping you from writing extremely messy React applications...
Project Manager: Now add 3 checkboxes, one being 'N/A' and when you select N/A the other checkboxes are disabled and unchecked. And update the labels, and have additional form sections showing depending on which checkbox is displaying.
Probably not that difficult, and probably a bad example, but with React/Vue/etc. it's a lot easier to deal with complex states than manually manipulating the DOM.
From experience trying to be clever and anti-framework ends up just creating another framework that's worse in every imaginable way.
Reactive frameworks do make your life simpler (at least once you pay for the large one time cost of using them), but the change isn't enormous.
All you need to do is call setState
Virtual DOM qualifies as clever in my book. :)
Better question to ask is why so many libraries/frameworks proliferate in webdev and not as much in native apps. JS is a suitably powerful language these days.
Also, the attitude of “just use jQuery like everyone else” (paraphrasing the last paragraph and substituting for React) would have precluded the development of React.
With native apps you definitely have frameworks available now. React Native for an example. But the languages and toolkits available basically serve as a framework anyway.
How to change this page to this other page as fast as possible, if you don’t know or don’t care to know that other page.
That second qualifier is really important. As long as you have 2-10 screens and know the transitions by heart, nothing stopping you from hand rolling js. But once you start adding states things get tricky really fast, as transitions grow exponentially.
I’ve built some very complicated apps with vanilla js back in the day, and we had ways of dealing with things like that. We called it “reloading the page” where you start from 0 with your state. Kinda like restarting windows to fix it, rather than figuring out whats wrong.
And you could get quite far that way. 37signal’s basecamp was like that - an html app with vanilla js sprinkled throughout. Worked great.
But there is a limit in complexity. JS and html are great for building websites, but if you want to build an actual application, you need to be really clever and accept a lot of limitations. React just lifts the ceiling of what you can do, without being all to complicated.
And you can use the technics of react without react itself too, once you understand what it is all about - https://github.com/ivank/vanilla-teuxdeux
One day React could change from using Virtual Dom to the Svelte way and most user of library wouldn't notice.
The point of the article is that React remember where to make the modification for you.
A better solution is to emulate the react strategy. Create a state object, on user input you can rewrite sections DOM based on the state. You probably don't need React's diffing algorithm until you run into performance problems. Then you have to limit which parts of the Dom you update to keep it snappy. Then you might as well just use react.
Casually dismissing others by strawmanning them with fake quotes is against the rules. Even outside of that, it's just generally the kind of thing that is neither respectful or respectable. Please don't do it.
Did you actually think I was trying to attribute that quote to op?
We can do better from here, mostly by hewing more to the functional core/imperative shell idea. Redux is a popular approach that shows the power of this. In more modern languages with ADTs you don’t even need a library/framework once you fully understand how to structure things well.
What happens when it's one of hundreds of checkboxes on the site? When they all do slightly different things depending on user sku, product page, file type, file permissions, god knows what else. And when one experiment flag is on or how about this other one? Then i18n? Then what about the fact that after you write this line countless other engineers will see and modify it in the future, it's not just you writing and maintaining it? These are the problems that my company (and, I assume, Publicis Sapient with 20,000 employees according to Google) have to consider when choosing whether to hand roll JS or use a framework.
You'll still have to tackle those complex requirements and come up with a good design that organizes things and makes them manageable, whether you're using React and JS or just JS.
To say that a good design is just impossible with JS or that no other engineers could possibly understand the resulting code seems absurd.
Javascript is a Turing-complete language. It gives you a lot of design options. Your poor engineers will have to learn it to use React anyway so why would vanilla js necessarily be worse than js plus a giant framework?
Buidling the next Google Docs or Notion app? Use React/Angular, etc.
99% of the people that use React use it to build the former and then debate endlessly about their little teets and toots of JSX, Redux, Router library, etc. FFS, it is overkill and unnecessary. Simplify, go home on time and enjoy your the time with your family.
Meanwhile I have seen SO MANY sites that use full React for a contact form with two fields on it.
> Meanwhile I have seen SO MANY sites that use full React for a contact form with two fields on it.
I agree that the contact form you describe would be dead-easy to do vanilla. Maybe throw in Parcel if you want to write ES6.
However, while I suspect some people may use React in this case because it's all they know, others may do it because they are literally faster in React - they have a workflow that can see them code and deploy such a website to Netlify or Heroku or whatever in 10 minutes.
Why introduce inconsistency in everyone's workflow just because this specific page is a simple contact form?
The fact that it is just a simple contact form is exactly why you should use the same tools and workflow that everyone in your team has already been using.
Write what other people knows so you don't have to be the one maintaining it.
But:
1) Even though the web-specific example is contrived, it's a good demonstration/explanation of what people mean generally by declarative vs imperative
2) I don't want to wade into the tired argument, but classic HTML + minimal hand-written JS doesn't scale beyond a certain point. If it did, everyone would still be doing things that way
What are the chances that you are arriving at a solution that is better than React? That other engineers have no trouble understanding and maintaining? You'd have to invent new concepts, or at least call them differently, to not copy React's (or any other framerwork's) concepts or ideas. That would make it harder for other people to understand the code.
Anything moderately complex gets really painful when you’re storing state in all your HTML elements.
A big part of React is to abstract away the horribleness of trying to prevent unnecessary, quite expensive interactions with the DOM.
That’s why a lot of comparison examples miss the point and facilitate poor discussion.
var checkbox = document.querySelector(
"input[type=checkbox]"
), container = document.querySelector(
"#wrapper"
);
checkbox.addEventListener("change", () => {
if (checkbox.checked) {
container.classList.add("checked");
} else {
container.classList.remove("checked");
}
});
Then use CSS to show or hide the message inside the container based on if it has class "checked" or not.You can get a whole lot done with very little code if you learn to take advantage of the three-legged stool of HTML, CSS and JavaScript.
container.classList.toggle('checked',checkbox.checked)Usually for things like that I'll come up with a CSS class that means "set it up so this element has its class toggled based on the state if the checkbox it contains". Sometimes I'll use data- attributes for additional configuration.
<input type="checkbox" id="discount">
<label for="discount"></label>
<style>
#discount + label:before {
content: "Click me to apply fake discount!";
}
#discount:checked + label:before {
content: "Click on me to remove fake discount";
}
#discount + label:after {
content: "You have not availed discount";
display: block;
}
#discount:checked + label:after {
content: "Discount Availed!";
}
</style> <!doctype html>
<body>
<custom-element></custom-element>
<script>
const CHECKBOX_ID = "my-checkbox";
const defaultLabelContent = "Toggle me, you newbies";
const beforeDiscountText = "You have not availabled discount";
const afterDiscountText = "Discount Availed!";
const beforeLabelText = "Click on me to remove fake discount"
const afterLabelText = "Click me to apply fake discount!"
const state = new WeakMap();
class CustomElement extends HTMLElement {
connectedCallback() {
this.render();
this.shadowRoot.addEventListener('change', (event) => {
state.set(this, event.target.checked);
this.render();
})
}
constructor() {
super();
this.attachShadow({ mode: 'open' });
}
render() {
let isChecked = state.get(this);
const discountText = isChecked
? afterDiscountText
: beforeDiscountText;
const labelText = isChecked
? beforeLabelText
: afterLabelText;
this.shadowRoot.innerHTML = `
<input
${isChecked ? 'checked ' : ''}
type="checkbox"
id=${CHECKBOX_ID}
>
<label for=${CHECKBOX_ID}>
${labelText}
</label>
<div>${discountText}</div>
`;
}
}
customElements.define('custom-element', CustomElement);
</script>https://codepen.io/uwwgo/pen/GRmEKJz
(nothing revolutionary, does the exact same thing.)
Your comment is fully correct, but I would like to point out:
- with such a tiny DOM to rerender, it is equivalent, probably even faster
- custom element encapsulates DOM and it is fairly trivial and extremely fast to pick DOM (like you can even use id's everywhere) in the 'old jquery' way, with simple library functions
- updating DOM with simple render() call is way more elegant, but if you keep custom elements DOM small (and one should), this way is not that bad at all
Like this:
<!doctype html>
<body>
<custom-element></custom-element>
<script>
const CHECKBOX_ID = "my-checkbox";
const defaultLabelContent = "Toggle me, you newbies";
const beforeDiscountText = "You have not availabled discount";
const afterDiscountText = "Discount Availed!";
const beforeLabelText = "Click on me to remove fake discount"
const afterLabelText = "Click me to apply fake discount!"
const state = new WeakMap();
// 'library' code
function qs(selector) {
return this.shadowRoot.querySelector(selector);
}
function getElem(nodeOrSelector) {
return nodeOrSelector === String(nodeOrSelector) ? qs.call(this, nodeOrSelector) : nodeOrSelector;
}
function replaceText(nodeOrSelector, text) {
let elem = getElem.call(this, nodeOrSelector);
if (elem) elem.textContent = text;
}
function updateAttribute(nodeOrSelector, name, value = '') {
let elem = getElem.call(this, nodeOrSelector);
if (elem) elem[(value ? 'set' : 'remove') + 'Attribute'](name, value);
}
// end of 'library' code
class CustomElement extends HTMLElement {
connectedCallback() {
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<input type="checkbox" id=${CHECKBOX_ID}>
<label for=${CHECKBOX_ID}></label>
<div></div>
`;
this.shadowRoot.addEventListener('change', (event) => {
state.set(this, event.target.checked);
this.update();
})
this.update();
}
update() {
let isChecked = state.get(this);
updateAttribute.call(this, 'input', 'checked', isChecked);
replaceText.call(this, 'label', isChecked ? beforeLabelText : afterLabelText);
replaceText.call(this, 'div', isChecked ? afterDiscountText : beforeDiscountText);
}
}
customElements.define('custom-element', CustomElement);
</script>I hope you’re comparing this to React? Because if you’re comparing it to vanilla JS that reuses the DOM nodes, absolutely not.
This article is absolute nonsense from start to finish. What amounts to basically "lying" about the complexity of vanilla JS actually ends up mainly just doing a massive disservice to React which shouldn't need false comparisons to show it's benefits.
Maybe they're just being disengenuous but I got the distinct impression from many of the examples that the author doesn't actually know vanilla JS at all.
You have to invent some elaborate local state schema and then map it to DOM, instead of keeping part of the state implicitly stored in DOM, where it makes sense.
You can assign your data directly to DOM node objects. Say `el.yourData = todo_item`. And then let the order and list of items be kept implicitly in DOM, so you can do obvious things like remove nodes using `.remove()` reorder them via DnD, and whenever you need the list as data, you just querySelectorAll('.item').map(el => el.yourData) and you have your list. All quite straightforward.
You can also do context dependent things by being able to travel up to the ancestors via parentNode.
Declarative frameworks like react make simple things like this painful in comparison.
Something happens
The browser triggers and event and sends it to React
React calls your code to re-render the world[1]
React takes the new world order and does a diff
React calculates what to do go from old -> new and applies
In VanillaJS world you can do way way way better than this with the benefit of knowing how your application works. Something happens
The browser triggers and event and sends it to your handler
Your handler updates the DOM
It would be nice if in future you could make some promises to React about what happens on an event so React can skip the diffing step and just update the virtual and real DOM directly. And hint hint if you can generate the code to update the DOM directly in the general case too then do you even need the virtual DOM? Svelte is doing really cool work in this space.[1] componentDidUpdate helps but same diff
I'm glad it's not easy to escape the paradigm.
I know there are cases where it's needed but it's rare (at least in my line of work).
I found this ironic, as I have never in my life had more struggles with state, than when working with react native. Seriously, the amount of times something didn't update, or was updating way too many times, is countless. It's so easy to shoot yourself in the foot. Imperative native programing, almost never have this issue.
Overall I prefer React because I prefer simple composable libraries over frameworks and Angular reminds me too much of programming in Java with its long application boot times and its folders full of ListUpdateCheckerConditionFactoryBeanUnitTest.java's.
*To be fair, in an equivalent React app, at that point you would have had to write a whole lot of shouldComponentUpdate to not tank performance.
The React haters here seem to think that is easy. But most of the popular frameworks/libraries use a virtual DOM in some way or another. And Svelte also automates handling the updating. Maybe it's not so easy after all, if smart people have spent decades trying to find alternatives.
This is what Svelte's doing, as I understand it: letting you think like you're writing React ("when in this state, the world should look like this") but avoiding the (greatly overstated, IMO) overhead of the virtual DOM by translating the changes into direct DOM updates in a complilation step.
I think I blame part of this on the language we use. These days a huge buzzword of sorts is the “zero-cost abstraction.” It means zero runtime cost, but a lot of us internalize it as completely free, failing to account for the fact that it often entails increased complexity and build times. Granted, often this is a worthwhile tradeoff, but in order to know you need a more nuanced comparison. That virtual DOM is “pure overhead” isn’t objective fact - pure overhead is an error of coding that can be fixed in a pull request. No, this is more like ideology.
The problem with this ideology isn’t that it’s bad, it’s just incomplete. It usually explains away why the world hasn’t simply adopted their worldview by appealing to ignorance or even stupidity, while ignoring potentially serious issues. Like yeah, if I want to make a desktop application in 2021, I have to consider Electron because simply put, there’s a lot broken in modern native UI.
And sometimes people are still right. There’s always a possibility Svelte will win out, or eventually be proven right even if it doesn’t.
Maybe. But it’s 2021, and the year of the Linux desktop is still around the corner. If something hasn’t happened yet, at least humor some reasons why that might be the case.
(Personally, in my experience, even update-intense apps wind up having bigger fish to fry than VDOM, so I can’t say I’m holding my breath.)
you can get pretty darn close to the react version of this example using vanilla js.
If you only mutate state on the server and simply send views back down to the clients, nearly all of "modern" web development practices can be safely ignored.
Clearly, there are difficult engineering challenges with the approach of "all state on the server all the time", but anything worthwhile is never easy. Down this path you might not obtain Netflix-tier webscale directly out of the box, but that doesn't mean we throw our hands up and have all our clients drown in multiple megabytes of angular11+ dependency trash either.
How many internet users are more than 50ms away from a Cloudflare/Microsoft/Google/Netflix CDN in 2021? How many cores can you get in a 1U server now? Distributed state machines for client UIs have been a massive mistake.
I think it's important to define early in a project if the app is "cloud-based" or "local-based". If it's cloud-based, then only the server mutates state and sends views to the clients, as you wrote. Everything is simple. If it's local-based, then all data are available locally and mutated locally. The cloud is only used as mirror/backup and can support for some advanced features like full-text search. That's also a very clear architecture. That's how Linear works.
Things become hairy and unnecessarily complex when no clear choice is made between those two options, then it's not clear where the state is.
There are real world challenges. There's no internet access on the NYC subway. Latency can spike for no apparent reason. Making a webapp a dumb client really only works for wired connections on an intranet.
When I was working in South Korea, their subway system had excellent reception to cellular and even satellite TV networks. They explicitly engineered a solution to this problem in direct, first order terms.
This is precisely the type of approach we should be taking in my opinion. Make the networks robust, not the client-facing web apps. We are spending engineering resources in largely the wrong places.
This would be like arguing for a car that can hover, but only for an ambiguous/non-specific amount of time, simply because the roads are occasionally total shit.
I try my best to build robust apps but have no bearing on my countries infrastructure plans. And have the government reallocate my resource to setting up antennae in tunnels is dystopian.
I completely agree. Sharing a layer of an application between client and server is a nightmare and will fly in your face.
That said, it is possible to cleanly handle more involved interaction on the FE and have a clean separation of responsibilities. When well done, the results are very snappy and robust. Of course, it isn't always necessary, and most RoR applications beat that 5mb Angular behemoth.
I wish software developers would be more honest about their tools, weighing their pros and cons, instead of thinking up contrived 'examples' that paint them in the best possible light.
Every library/tool/framework will make you think "well, this sucks" at some point. So be honest.
If anything, this article is an example of how you need to write and truly understand vanilla JS (and learn form your mistakes) before you can appreciate and understand what react had to offer when it first came out.
I might have to write a counter blog post just to balance this out...SMH.
I remember using jQuery, Backbone/underscore, handlebars, knockout, Angular 1, Enyo, Ember, and probably a couple others. Angular in particular had like 70% market share among major frameworks and almost all the libraries didn't support React.
React took over because it was head and shoulders better than everything that went before and taking days to learn instead of weeks or even months.
The reason nothing has taken over since is because we've reached the point where they aren't good enough to justify throwing away all the existing library support.
And yet this article is disingenuous. The OPs target can be achieved using CSS alone. In fact, quite a lot of things can be done quite well in vanilla JS and CSS.
This works well to some degree. Then I found it to fall apart.
- Those BE devs now forced to write FE in React|Vue|* and hate it so much that they've never learned it, won't learn a vanilla stack either. Especially not CSS. That's just for colours. Or something.
- Most vanilla approaches I worked on relied heavily on the correct ordering of HTML elements with the correct classes for something to work. There's little to no encapsulation. Only copy and paste. It's also immensely brittle.
- You can add some simple encapsulation, but the easier way is to brute force some imperative mess. Close ticket. Open next. Velocity is high.
- The next step is to build your own framework. But chances are it will be worse than any 3rd party solution.
- A huge advantage of 3rd party libs is that there's zero chance of some ticket specific code to erroneously make its way in to the framework. Silos aren't always bad.
- Onboarding new devs is hard. There's probably no resources at hand.
- At this point you've tied yourself in to knots and the actual problem, your product, isn't even close to being solved.
It takes less than an hour to have a fast React|Vue|* application off the ground. Everything you need to build the product is in place. And with some care, it will remain fast. Alternatively, Ruby on Rails and friends work just as well.
However, wasting endless hours reinventing a worse wheel is unproductive.
For a real "ground up" approach of explaining those I'd recommend this article series: https://acko.net/blog/climbing-mt-effect/
Your heard me correctly, you can create components with JavaScript without the aide of a framework.
But once you have to display lists of stuff with lists of other stuff inside you basically need a template library otherwise you're going to be doing some pretty weird DOM manipulation to copy sections of elements.
So a comparison that might resonate better with folks here might be to have a pure JS TODO app with a comment section in each list item. It becomes harder to express in pure HTML. You'll want some template library to keep it maintainable.
If your lists are long enough, you probably want to split what you can actually display from the rest of the list, because even today updating the DOM with thousands of nodes is expensive. And doing seems to be easier and less chatty to do on the front-end I think.
Reminds me of all the "yaml is better than XML/JSON" examples where everything is carefully formatted in a way that make no sense unless you are trying to prove a point.
Part of me think we should just ignore html and just render everything using webgl/webvulkan/whatever instead of fighting the browser's flow. We're not there yet but things have been moving in that direction because it kind of makes sense
I lived thru the Java AWT to Swing transition. One of Swing's Big Ideas was for every component (aka view & controller) to be backed by a separate model, finally mainstreaming the MVC design pattern.
Then of course all the web frameworks got nutty over MVC.
My only takeaway from the many, many MVC debates is that the only way to win is to not play.
At least vanilla js version doesn't re-render the whole component.