DEV Community

Cover image for Svelte for Sites, React for Apps
swyx
swyx

Posted on • Edited on • Originally published at swyx.io

Svelte for Sites, React for Apps

Translations: 中文版

In 2020, my personal recommendation to web developers is to use Svelte for Sites, and React for Apps. This is, remarkably, a nuanced enough opinion that it pisses off fans of either of them.

I mentioned this in my Shoptalk Show interview and Chris Coyier encouraged me to blog about it. Let me try to explain.

Sites vs Apps

First, I have to make a distinction between (Web) Sites and (Web) Apps. There are serious, intelligent people who insist that there isn't one. They want to build everything on the web with the same tech. Respectfully, they are wrong.

Web Sites primarily display content, while interaction is limited. First-load times are paramount since users may bounce and/or their limited data/power/CPU may deprive them of important information (see Alex Russell for math on a reasonable baseline but let's say you definitely want <200kb in the critical path). This was the web's original usecase - displaying information - and it is what HTML/CSS/Browsers are great at.

Web Apps primarily exist for interaction. CRUD apps, livestream apps, games, whatever. These apps tend to be heavier, which is unfortunate because that affects their performance. But even a 2MB JS app doesn't sound so bad when it is literally competing with a 200MB mobile app, and (let's say) you're developing a B2B app where everyone is on high power and high bandwidth devices anyway. You're typically also keeping apps open longer, so the first-load issue doesn't matter as much (and can be mitigated with service workers). The challenge is even higher once you account for the fact that the Web App must ship with it all the UI components and behaviors for it to work, whereas a typical native app will usually heavily lean on platform-provided components. The web platform still lacks a lot of standard components/APIs and developer experience needed to make writing great Web Apps easy - hence the gap is filled by frameworks.

I view Sites vs Apps as a spectrum. Of course, if your sites dont need ANY interaction at all, don't use any JS. But most sites have app-like features (login, reactions, comments), and many apps need to perform under site-like constraints.

Aside: Check out Jason Miller's Application Holotypes for more thinking on matching the architecture of a web project to its intended use.

You'll notice that most businesses already recognize this - www.mysaas.com is the marketing site, app.mysaas.com is the app. They may start out the same codebase, but due to the vastly different requirements, they eventually split into different codebases and then different teams handling them. It's usually the idealist enthusiasts that try to make the same tech work for these clearly different purposes.

React for Apps

React has been open sourced for 7 years now. It is used in production at the biggest companies and sites in the world from Apple to Twitter to Amazon to Airbnb to Uber. It has been the most cited technology in Hacker News job postings for at least 36 straight months. There are between 3-9m React developers, growing at least >50% annually. The third party ecosystem is vast and attracting instructors, developers, companies and hundreds of millions in corporate and venture funding.

Based on that alone it is a good tech choice to base your app on already. But these are contingent facts that don't really have anything fundamental to do with React's merits. This is offensive to first principles thinkers. So let me offer some core reasons why React is a great choice for apps:

  • React Native looked troubled in 2018, but the current team seems to be executing well (as far as an outsider like me can tell). Flutter may yet give it a run for its money someday, but has the Dart and Google hurdles to overcome. React Native is the best cross platform (mobile+web+desktop) "Write mostly once, run mostly anywhere" solution in tech today. If you have the resources to hire platform specialists, you won't find this useful. However, if, like the vast majority of companies, you can't afford a dedicated team of specialists per platform, React Native is your best bet.
  • React has by far the most experience in abstraction design. Where React leads, other frameworks follow (Both Vue's Composition API and Svelte 3's $: API directly credit React for inspiration, as do Swift UI and Jetpack Compose). This isn't to say they always get it right (pop quiz: how many Context APIs are there in React?) but when Concurrent Mode and React Flight are released, I expect it to be deeply informed by production usage at the biggest websites in the world. Suspense for Data Fetching, still not yet released, has been in production at Facebook for over a year. I want to stress how unusual this is - typically in open source, you release something and then hope it gets picked up by a BigCo and tested at scale. With React, Facebook dogfoods it at scale before releasing to the general developer community, with many ideas killed before they are publicly blessed, because flaws were found. Judge React as much on what it doesn't ship as you do on what it does ship.
  • That brings me to governance. It's not perfect (many people have issues with Facebook, for one thing), but I think React is one of the best run open source projects in the world. Normally mundane things like versioning policy to error messages to release channels to gradual upgrades matter at the scale of React. The team also does a lot of informal collaboration with key ecosystem partners like Gatsby, Apollo and Next.js, including at the browser level with Chrome and the language level with TC39. The team not only deeply cares about technical governance, but also fostering an inclusive and diverse community.
  • I hesitated to mention this last point because it technically has to do with adoption, but I cannot separate it from React's merits: it seems to have the best thinkers on accessibility and interaction design right now. No other ecosystem has projects like Adobe and Devon Govett's React Aria that has extensively thought through and tested for WAI-ARIA so you don't have to. Ditto Segun Adebayo's Chakra UI. Or listen to Rick Hanlon on the Touchable Web and realize how much web apps need to improve for the open web to reverse its alarming decline vs. mobile walled gardens.

    • Let me be clear - is the React community ACTUALLY good at these things today? Hell to the no. Most of them are still debating whether or not to learn hooks vs class components. BUT React has the best shot because it has the best abstractions that enable the best thinkers to create the web application standard library we all want.
  • Selective and Progressive Hydration are particularly interesting results of the Fiber rewrite. Together with a "full stack" future of React that lets the developer easily move code and execution between client and server, the hope for making apps that feel fast without compromising on developer or user experience is extremely strong.

You can, of course, use React to make sites. Gatsby and Next.js (and the upcoming Remix) are great static and serverless rendering options (The "greatness" of Gatsby is disputed). Docusaurus is great for docs sites. If you are making sites and are worried about JS weight, you can usually swap Preact for React in a few lines of code because you will usually not be running into any of Preact's compromises if you are just making a site.

So why do I advocate using a different framework for sites?

Svelte for Sites

Specifically, Svelte for Interactive Sites

Svelte is used in production
from the NY Times (of course) to Square Enix to Apple to Spotify to Google Arts to Alaska Airlines and hundreds more, with other big dev platforms like Amazon and Microsoft also increasingly featuring it in their content. It has a lively community with the first podcasts, YouTube channels, schools, conferences and newsletters emerging. Svelte 3 has been wildly successful and yet it is still early days.

I'm going to let you in on a little secret: Svelte and React aren't that different. Take a look under the hood of Svelte compiled output:

function create_fragment(ctx) {
  // redacted
}

export default class App extends SvelteComponent {
  constructor(options) {
    super();
    init(this, options, null, create_fragment, safe_not_equal, {});
  }
}
Enter fullscreen mode Exit fullscreen mode

Wtf? class App extends SvelteComponent?? That looks like React??

Yes. Wait til you realize that = basically compiles to setState, or that yes, it does actually ship a runtime, or that yes, it actually has a scheduler too. Like I said, where React leads, other frameworks follow. React proved Components are the right way to go.

This also means that most React developers can learn Svelte in hours so the switching cost is low.

The differences are large enough, though, in everything else:

  • JS Weight. Your site might get green Lighthouse scores, but hopefully you agree that you ideally only ship JS that you use, for your users' sake. Svelte sites are often single digit kilobytes. React+React DOM is ~120kb uncompressed. You can of course slash this severely if you can switch to Preact. But Svelte offers the smallest measured runtime footprint. We used to worry about the compiler output overhead exceeding the size of React components (smaller runtime = more boilerplate), but recent studies have debunked this concern completely.

    • But my consideration of JS weight extends beyond just the framework. Anecdotally, the kind of people that are drawn to Svelte seem to be more performance-minded than those in React (see everything that lukeed makes). This comes from the top - where React devs often import heavy dependencies as long as they kinda fit the usecase, Rich Harris is the kind of stubborn developer that makes his own version of everything because he just needs it to do a smaller job. But also, Svelte is most people's second framework, so they come to it with more of a performance mindset. Collectively, the dependency choices encouraged by the framework's culture also impact the end result of JS weight.
    • I am even encouraged by the emerging JAMstack culture in Svelte, where Nick Reese has made an excellent implementation of Jason Miller's Islands Architecture with Elder.js. (TL;DR - typical Gen-2 SSG's send JS to rehydrate the entire page, even the content that doesn't change, whereas Islands Architecture sites only send JS to hydrate dynamic parts of the page and leave the rest untouched.)
  • Scoped styles. Need I say more? The way Rich Harris puts it, goes something like this (poor phrasing is my fault): "In my opinion, a frontend framework should give you a styling solution" (fun aside: watch the React Core Team debate styling solutions! They feel the pain). Not just styling, but transitions and animations too. Ask any React developer what styling/animation solution to use, and watch them squirm or give you a PhD length dissertation of 5 subtly different alternatives. I say this with some irony, because I myself use Tailwind with Svelte.

  • Full Sitemaking Toolkit. It's not just styles and animations. State management? Head management? Class toggling? Tween/Spring effects? (soon) Routing? All are one import away. Because of Svelte's design, you can use as much or as little as you like, but at least there is a first party option for everything.

    • React takes pride in its minimal surface area and relies on its ecosystem to fill in the gaps. Choice is good and a big part of React's popularity and longevity.
    • But I've lived with the ambient anxiety of having to stay informed and choose and set up every goddamn part of my frontend stack for years at this point, and it really is not productive. Look, maybe I just suck at this. Or maybe I just need a more productive stack that aligns with my preferences.
  • Svelte is a superset of HTML. Svelte is actually not just a toolkit, it is also a language designed to make the web developer more productive. That means that SVG "just works". That means that you can work with classes. That you can work nicely with Web Components (both exporting and importing). A lot of little things you make apologies for with React and JSX.

  • Svelte's downsides matter less when making sites. Svelte has a much smaller ecosystem and community, but that matters less when you're making sites, since you're going to be mostly making your own designs and interactions anyway. This is certainly how Rich uses it at the New York Times - not relying on the ecosystem. The smaller hiring pool is also less of a concern since you typically wouldn't be hiring the same size team you'd need to maintain an app.

    By the way, we are working on building out the Svelte ecosystem by helping to grow the Svelte community - Svelte Society was started a year ago in a dinky little Microsoft room - check out Svelte Summit if you are reading this on 18 Oct 2020!

  • If you STILL needed to ship features in React, you could mount it atop of a Svelte app if you wished. It would make less sense (because you'd already be paying the library footprint size) to do the opposite, so it just makes sense to have Svelte as the baseline.

Aside on Render Performance and Virtual DOM: The importance of a "Virtual DOM" is a big bone of contention between React and Svelte (Tech Twitter folks will remember the 3d "benchmarks" from last year)) but to be quite honest the kind of pedestrian sites and apps that you and I write don't even run into that kind of perf demands, so I don't count it.

I've written more thoughts on Why I Enjoy Svelte, but these are the two salient points that lead me to pick Svelte over React for my own interactive sites.

Why use frameworks at all?

Of course, webdev being webdev, we aren't done discussing the full complexity of this sort of tech stack choice. The other concern people have comes from the opposite direction - if you're just making a site (interactive or otherwise), why use a framework at all?

It's a valid question - after all, perfectly good, fast, battle tested solutions exist from Hugo, Jekyll, Eleventy, and so on. They generate zero JS by default, and then let you "sprinkle on JS" as needed.

My current answer here is more about mental model. I want to code using components, and I want an easy upgrade path to add interactivity to something that wasn't previously interactive. None of those more traditional site generators let me do that. I'm not sure that this line of argument is convincing to the "no frameworks" crowd, but it is true for me.

The Philosophical Big Picture

I want to share with you a deep realization I had, that is going to sound extremely underwhelming at first:

Tools-designed-to-make-small-things should work very differently from tools-designed-to-make-big-things.

Well, duh, right? At the surface, this is just a restatement of the tired "Use the right tool for the job" cop-out, which I have my problems with.

But no, this is subtly different. I am insisting that what looks like the same job, at two different scales, are actually different jobs. Different enough to justify using different tools.

Further, when we ignore this and try to make the tool do everything, we make the tool worse for everyone - more confusing to learn, more API to remember, and often a degraded end user experience from making too many tradeoffs.

In the rush to satisfy everyone, we delight no one.

Aside: The reasons we do this are complex. Sometimes devtool companies do it because they feel they need it to grow. Other times hackers just do it just to show that they can. I pass no judgment here, it is always worth trying to push limits.

This is the high level takeaway I have in the React vs Svelte debate. It's exposed most clearly in the public statements that the React team have been making (PLEASE DO NOT CROSS EXAMINE THEM ON THIS, THESE ARE MERELY OFF THE CUFF STATEMENTS ON PERSONAL SOCIAL MEDIA):

  • Dan Abramov: "A “disappearing framework” is certainly cool and worth striving for. But it doesn’t help much when the framework is 5% of your code. Say “disappearing app” and I’m listening."
  • Seb Markbage: "This is from an internal perf investigation I did. We also see similar numbers in all real significant apps. This is the percentage of all JS time and about 5% is the time spent creating the actual DOM nodes so it’s inherent. The framework code is about 8%. We could optimize those 8% and use various other tradeoffs. To save maybe 7% of JS execution... However that hides 87% of the JS executed in actual apps. That’s what we need to focus on."
  • Dan again: "I think overall it's true that we're a lot more focused on optimizing the application size over the library size. Because the library size is relatively constant, whereas the application size keeps growing. lazy() is an example of that, but there is a lot more we need to do."

The thing is... React's library size is 120kb (uncompressed). What size of app are you targeting for React to be 5-13% of total JS? 1mb-2.5mb. Is your site/app anywhere close to that?

The ground facts are these:

  • React is without question the best framework for making apps and getting better
  • the React team is more focused on apps than sites
  • While they really care about community, React is made for Facebook needs first and foremost
  • You Are Not Facebook
  • Your site is most definitely Not Facebook
  • You probably don't use all the features React ships
  • Even if you use Preact instead, the P/React ecosystem doesn't give you enough out of the box to be productive
  • There should exist a better and different toolkit for making interactive sites.
  • The best langauge for that today is Svelte.

Svelte for Sites, React for Apps. Q.E.D.

P.S. for the apoplectic Svelte fans: yes of course you can use Svelte to write Apps too. Let people realize that on their own. Make the case where you can indisputably win, where adoption is easy and lower cost, rather than fight every battle on every front even where circumstantial facts weaken your case.

Top comments (90)

Collapse
 
mvolkmann profile image
Mark Volkmann

You keep pushing this point and I keep not getting it. I think I won’t be convinced until you can provide a list of things that are easier to do or better implemented in React than in Svelte. I can’t think of anything off the top of my head that works better or is easier to implement in React than in Svelte. On another note, I think it was bad timing to publish this the night before Svelte Summit.

Collapse
 
swyx profile image
swyx • Edited

i dont agree with the premise of the question, but fwiw my list is in the blogpost. here is a summary.

  • hiring
  • 3rd party ecosystem (eg react-aria, material-ui, react-testing-library, redux, apollo, framer/framer motion, styled-components etc). Most companies, like AWS or Stripe, offer React SDKs before supporting any other framework.
  • react native
  • (in future) suspense/react flight
  • governance

first two points are sufficient for people to make tech choices already. yes i understand that these are not central to the framework. doesnt matter. early-to-late-majority adopters don't care. they care about ecosystem.

what matters is where does svelte have an indisputably clear advantage TODAY. i wrote the final P.S. with this message in mind. "Svelte for Sites" is as much a convenient lie as an adoption tactic as it is an inconvenient truth because of the abovementioned factors.

blogpost timing also doesnt matter. we both write with a more evergreen perspective and honest discussion is always a plus. but acknowledged that you disagree.

Collapse
 
mvolkmann profile image
Mark Volkmann

I agree with you on the React Native advantage. We’ll see if Svelte Native continues to mature.
I don’t yet understand the significance of Suspense and Flight, so I can’t comment on those.
It’s just a matter of time for the Svelte ecosystem to sufficiently catch up.
The hiring issue is minimized by the fact that Svelte has a low learning curve.
I think what triggers me most is the implication that Svelte should only be considered for sites. I’ve successfully used it for many apps. I don’t want developers to get the idea that Svelte is somehow lacking for real app development.

Thread Thread
 
lepinekong profile image
lepinekong • Edited

Personally I would choose Svelte but for big project of xx millions like in big corps I won't because actually hiring issue cannot be minimized : most already-heavily-invested-in-a-framework developers will just refuse to learn another (new) framework ;)

There are other reasons, I just pick the one argument you advance.

Thread Thread
 
swyx profile image
swyx • Edited

don't worry, I'm with you on the core capabilities of the framework. but ecosystem matters when building apps. plain and simple. part of what I'm doing here and with svelte society is laying the groundwork to address these issues, but it will take years. in the mean time, market to the usecase svelte wins hands down.

we agree more than we disagree.

Collapse
 
ascotto profile image
Andrea Scotto Di Minico • Edited

Can totally agree on the first two points: for me transitioning from jQuery/javascript to React engineer made the biggest impact on my pay-check, and a better engineer overall. Knowing and increasing the expertise in React gave the power to negotiate better salaries/contracts, work at better companies and overall made a huge positive change in my life. Beside all this, I am also able to start my micro company with my girlfriend about frontend consulting (website needs to be finished hehe..)
Developers sometimes should shift mentality non just thinking how to do something with a "framework" but also how will this impact my life outside of my career.

Ecosystem is big, with lot of resources, and the are tons of open source project where you can find a lot of useful code and patterns.

Before trying React I wanted to learn Vue, I learnt some this was soon after release of version 1.0 of Vue, and at the time could not include in any final production project.

With Svelte, I made a little dynamic form on a WordPress site to test it out, was pretty happy with the outcome, the issue I had there was: if the site has already jQuery should you add Svelte for just a component?

As the final judgment: from my standpoint I would switch to using Svelte for website only if I cannot achieve the desired performance with React/Preact, and if there is not already jQuery.

Thread Thread
 
swyx profile image
swyx

JQuery is still a lot heavier than svelte. I'm not sure if WordPress websites ship with JQuery by default or something, but if you can remove it then I'd explore replacing it with svelte. components are just much nicer to write with, tho that is a subjective opinion

Thread Thread
 
ascotto profile image
Andrea Scotto Di Minico

Worpdress websites all ships with jQuery, and all the frontend depends on it, specially if there are using a template. Replacing jQuery on a Worpdress website will be a big headache because you need to replace everything of every additional plugin. Also if the client is using Woocommerce is something is not worth doing, in my opinion.

The only way to use Wordpress effectively with React/Svelte would be as an API endpoint or, let’s call it as a headless CMS.

The new Wordpress builder block is also made with React, so there is better tooling with React around Wordpress, at least at the moment.

At the end of the day what is important is regardless of what you use:

  • are you happy with the DX of the the tools you are using
  • is the client happy
  • are the clients users happy
  • clients and end users does not care what is working behind, they just care if it works well or not
Collapse
 
btakita profile image
Brian Takita • Edited

My experience is the hiring & 3rd party ecosystem is unreasonably effective at convincing people who do not want to look deeper into the workflow & architectural distinctions when making a decision. They want to make a quick decision based on numbers & will ignore any other reasons for considering a decision.

In reality, hiring & 3rd party ecosystem don't have much of an impact, and may even have a negative impact, on the success of a project. Being able to hire any Tom, Dick, or Harry who just graduated the most popular Programmer Bootcamp floods the talent pool with formulaic, inexperienced, & unimaginative developers. I'm not saying new developers are necessarily low quality, just that low quality developers tend to leave the software development profession when they realize it's not their calling within a few years. Sadly, many of these low quality developers move into technical management and have an even bigger influence over tech decisions.

Better talent tends to self-congregate toward better tools to augment their talent. I would prefer to work with a smaller talent pool with better talent than a larger talent pool with diluted talent.

3rd party ecosystem means more dependencies of varying quality & maintenance burden.

Collapse
 
ajcwebdev profile image
ajcwebdev

React also has significantly more developed meta-frameworks.

Thread Thread
 
swyx profile image
swyx

yeah I count that as part of 3rd party ecosystem advantage

Collapse
 
trashandfire profile image
trash-and-fire • Edited

Better implemented in React:

  1. Error boundaries (not implemented in Svelte).
  2. Whitespace skipping. Svelte is a superset of HTML with meaningfull whitespaces between inline-block elements.
  3. Typescript support. Try to write and publish any Svelte module in Typescript.

Also Svelte lacks of good tools, templates, IDE support and etc. For example: svelte-loader restarts css pipelines for ALL files in project instead of changed one. The svelte library template uses Rollup by default to bundle library in single file, all dependencies will be inlined into module and can't be deduped and shared between multiple npm modules.

Collapse
 
spacedawwwg profile image
Paul Welsh

These are "developer experience" related opinions, nothing to do with the output for the end user.

Collapse
 
danawoodman profile image
Dana Woodman

Coming to this way late, but for #3, that isn't so much of an issue anymore with pretty decent TS support (though not perfect)

Collapse
 
codechips profile image
Ilia Mikhailov

Performance and size are two factors that often can be optimized, but what about DX? Ever had to add forms to your React app? Spent time deciding on which forms library is best, finally went with Formik, and then spent half a day trying to find the optimal integration way for just your app. Ever got lost in hook hell? Are you sure you understand how useEffect works and where you should use it? My point is, React is overly-complicated and React fatigue is real.

I think that you should use technology/framework that makes you most productive while reducing your cognitive load at the same time. Newbies often jump on the React bandwagon because it comes from a big company and "everyone is using it".

I don't blame them. After all, it's where the money and jobs are. But do I feel sorry for them, because React is not easy to learn and IMO not a good first introduction to web development.

Also, JSX should be a low assembly language instead of something you write your apps in. Change my mind.

Collapse
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Also, JSX should be a low assembly language instead of something you write your apps in. Change my mind.

Not sure I know what this means. JSX is just another way to write HTML, except it's in JavaScript and gets compiled to HTML. I'm not sure how it's even comparable to assembly...

Collapse
 
peerreynders profile image
peerreynders

JSX is just another way to write HTML, except it's in JavaScript and gets compiled to HTML.

It compiles down to JavaScript React.createElement calls - not HTML.

JSX sees itself as an XML-like syntax extension to ECMAScript (i.e. not HTML).

So the common complaint is "what is this XML doing in my JavaScript code".

"I still maintain that JSX is pretty horrible."

Thread Thread
 
aleksandrhovhannisyan profile image
Aleksandr Hovhannisyan

Yup, you're right, JSX compiles down to React.createElement calls, which create elements (JSON blobs really) that describe UIs. But at the end of the day, these just translate into native DOM render calls. "Compile" was a poor choice of wording on my part :)

Having worked with React for about two years now, I honestly don't see the problem with JSX. It's an excellent, declarative syntax for creating UIs.

Thread Thread
 
peerreynders profile image
peerreynders • Edited

(JSON blobs really)

Naahh... React Elements ... which if I understand correctly are more generally vnodes.

"Compile" was a poor choice of wording on my part :)

It was the "HTML" that prompted me - "compile" is often used where "transpile" is appropriate - the issue is when people see JSX as markup rather than function calls; HTML only gets generated for SSR, not for client side rendering.

I honestly don't see the problem with JSX. It's an excellent, declarative syntax for creating UIs.

JSX as part of a sequence of JavaScript statements can be quite imperative; e.g. Marko's components are more declarative - the imperative behaviour of the component is clearly separated from its rendered representation; no "context switching" while reading JavaScript code.

But clearly there are people on both sides of the fence.

Collapse
 
codechips profile image
Ilia Mikhailov

So is it JS or HTML? Just kidding, of course. To me personally JSX always felt low level, something that is better suited to be generated by a machine from some higher templating language and then compiled to HTML. svelte-check tool does this to validate Svelte's templates for example. But the good thing is that we all have freedom of choice. Use whatever makes your heart beat.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

If you are talking about compiled Javascript (e.g. es5, minified), I think it is always Hyperscript, not JSX.

Collapse
 
seanmclem profile image
Seanmclem

Everybody is different.

Collapse
 
swyx profile image
swyx

deep

Collapse
 
khrome83 profile image
Zane Milakovic

I am less concerned with the tech. I even think Svelte is overkill for marketing sites. Yes, it’s smaller by a lot than react. But it’s also still worse than a jQuery site, a Alpine, or better yet, a vanilla JS site.

But it really comes down to balance. How much do you invest in getting the smaller site, vs a faster development life cycle.

Collapse
 
swyx profile image
swyx

what? a svelte site is almost certainly going to be smaller than jquery.

and the easy styling, animation, state mgmt, etc offer a faster dev life cycle to me.

but you do you man. just sharing my own thoughts.

Collapse
 
khrome83 profile image
Zane Milakovic

So it really depends on what you need. My gripe is not what you are writing but the fact you are turning everything into a component that does not have interactivity that needs rerendering, like header, footer, etc.

We spend so much time worried about the developer lifecycle. But we never let HTML and CSS be those things. We keep wrapping them in JS.

Svelte is better than React, and you can bail out with CSS by using custom or tailwind. But most people are doing CSS in JS. It’s just overkill for the user.

JS parse time of bundles on the most popular phones is shit. Once again I am talking about true marketing sites. Not apps.

But if you went vanilla JS, the bundle for sure would be smaller. Even jQuery could be smaller than converting all static HTML into Svelte components.

I am ignoring that you can sprinkle Svelte in, since most sites adopt it for everything.

Thread Thread
 
swyx profile image
swyx

hence my point about Islands Architecture and Elder.js. We agree!

Collapse
 
ryansolid profile image
Ryan Carniato

Yeah I wonder how light these straight from the CDN solutions are. Modern JavaScript tooling does amazing things. I was growing especially suspicious of these lightweight JavaScript solutions, both from size and perf perspective. So I added Alpine to everyone's favourite JS benchmark: krausest.github.io/js-framework-be.... It's neck and neck with Microsoft Blazor on perf and is by no means small. What are we really trading.

Collapse
 
swyx profile image
swyx

can you TLDR the alpine results? I find this table hard to read

Thread Thread
 
ryansolid profile image
Ryan Carniato • Edited

Alpine isn't large by any means but any size conscious modern library is going to via treeshaking going to produce smaller bundles than something that isn't prebundled. Alpine isn't treeshakeable currently (2.7.0).

Memory overhead is similarly middle of the pack. It's decent but again optimized libraries are still more performant.

Performance is not a motivation to the point Alpine is one of the slowest JS libraries I have ever seen. Orders of magnitude slower even for simple update operations like updating or selecting a row. If you use it sparingly as intended you will probably not notice but scale up that usage even a little and you will.

Basically, a library like Svelte is better by every performance metric if you can get over having to run npm i.


Explanation (for those who do want to take a minute to read):

The tests are basically a giant list management example like a TodoMVC where we are doing simple create, append, update, select, swap row, remove row, etc.. with enough rows and under CPU throttling from chrome browser to see differences between most common UI libraries. This is not the Realworld demo by any means only using the amount of features one might see in a simple admin management app. Styles are bootstrap etc...

One test measures the kilobyte weight of all assets sent over the wire. Nothing in the test is gzipped just minified. The smallest implementations come in around 143kb. Some notable results:

  • hyperapp 144.4kb
  • svelte 145.9kb
  • solid 149.5kb
  • preact 154.8kb
  • lit-html 156.5kb
  • inferno 162.9kb
  • alpine 167.9kb
  • mithril 175.2kb
  • vue 3 196.1kb
  • knockout 207.8kb
  • react 260.0kb
  • angular 295.3kb

Performance is not nearly as favourable. I respect that Alpine isn't really made to render 1000 components on a page. But how about selecting a row in a large list:

  • solid 24.8ms
  • svelte 37.1ms
  • hyperapp 45.3ms
  • inferno 49.6ms
  • preact 65.0ms
  • angular 78.3ms
  • lit-html 85.4ms
  • react 87.9ms
  • knockout 137.3ms
  • vue 3 164.7ms
  • mithril 270.5ms
  • alpine 1377.7ms

Or updating every 10th row with some additional text:

  • solid 143.9ms
  • inferno 149.3ms
  • knockout 160.0ms
  • hyperapp 160.1ms
  • preact 160.7ms
  • lit-html 168.0ms
  • angular 170.8ms
  • svelte 171.8ms
  • vue 3 183.9ms
  • react 188.6ms
  • mithril 242.1ms
  • alpine 1395.1ms

Finally looking at runtime memory with all list items on the page Alpine is middle of the pack again:

  • solid 2.2mb
  • lit-html 2.5mb
  • inferno 2.5mb
  • hyperapp 2.7mb
  • svelte 2.7mb
  • alpine 2.9mb
  • mithril 3.5mb
  • vue 3 3.5mb
  • preact 3.9mb
  • react 4.0mb
  • angular 4.2mb
  • knockout 11.6mb

*** obligatory disclaimer: this is a single benchmark scenario and not representative of all realworld apps... yada yada...

Thread Thread
 
khrome83 profile image
Zane Milakovic

So, I appreciate all your stats but your really missing the point.

Svelte is not smaller than Alpine. Take a standard marketing site where the header is just links. Nothing dynamic. These are still svelte components that have Javascript. But it should just be HTML.

I have a Sapper/Svelte site in production that is 126 components, but the number of those components that actually need to be dynamic on the client is less than a dozen.

And none of them have realistic performance concerns that I could not swap it out to Alpine and have the same experience for the user.

BTW Svelte and Alpine both modify the DOM and not a shadow DOM. So performance characteristics would be similar, which the exception of startup, where alpine has the parse live instead of having a JS bundle.

Tree shaking argument is mute, since Alpine is a actual library. Your not tree shaking your code. Your code is in HTML in most cases. You get too complex, use a library for a App. My argument was just simple marketing sites.

Thread Thread
 
ryansolid profile image
Ryan Carniato

Yeah you are right it's deeper than that. If we aren't doing the same work they arent going to be close. Which makes Elderjs interesting since it potentially could. But that also suggests JS on the server. So it isn't a swap in. But it is interesting such an approach could ship less JS. If Svelte itself is smaller and us only hydrating the necessary components.

Thread Thread
 
khrome83 profile image
Zane Milakovic

That would be my happy place, if we could declare what should actually be convert to a live component, vs what should be static html and is just using the life cycle to render, with a dapper framework or something similar.

Thread Thread
 
ryansolid profile image
Ryan Carniato

I'm fairly confident this direction is viable given Marko has been doing this at eBay since 2013. Who it is viable for is a different question. It will be interesting to see more libraries take this approach.

Collapse
 
ryansolid profile image
Ryan Carniato

Oh man this is heating up. Elder.js is interesting. MarkoJS has been doing this high performance partial hydration thing for years but I hadn't seen many other libraries make much progress here. Some had succeeded at skipping processing overhead but few the same sophistication of shipping less JS in completely automatic isomorphic way. That's very exciting.

I don't think the lines are that cut and dry. I mean I get from personal experience the small bundles and high performance attracting marketing and eCommerce. But Svelte's techniques don't preclude you from the application space. Conversely, there are sites that operate at massive scale that benefit from constructs beyond someones blog site. React might be structured better for applications and their orchestration features are designed to scale. However, look at how Svelte scales with feature use.

I get the right tool for the job thing, but Svelte's approach changes the rules. Modern bundlers are amazing. The right architecture could scale on features like Svelte with the philosophy of React. A bundler like Rollup can literally rewrite the code to the degree a feature as deeply invasive like Concurrent mode can be tree shaken right of the core of a library. How long before we see a bundler be able to code split a single module? What if you could opt in to pieces of the framework in different chunks?

Now I'm not going to say everyone picks up a library like that. People like Vue or Svelte for this simple entry point and Vue is very proud of it's progressive learning curve. So presenting things the way React does out the door might not suit everyone and that might be sufficient to give libraries specializations.

But I'd argue if anything Svelte has shown us there is very little stopping us from having it all. There is so much that hasn't been explored here. This doesn't have to be so versus. Both sides with time can learn from the other. But maybe that's something for the next generation of libraries to worry about.

Collapse
 
swyx profile image
swyx

indeed. maybe in a few years I'll be writing "Svelte for everything". but per my final section, I really doubt anything scales well from the smallest sizes to the biggest sizes.

Collapse
 
ivan_jrmc profile image
Ivan Jeremic • Edited

All UI libs that use wired template syntax for conditionals and so on like Vue and Svelte are garbage React nailed it with JSX nothing new they used what the JavaScript language anyway has and this is creating elements, all they did is changed the syntax of the createElement function to look like an element no matter how hard this JSX haters try with overcomplicated magic to beat react there is no chance React is king!

Collapse
 
devimposter1 profile image
devimposter

JSX is an ugly mess, using both Vue and Svelte very happily but sure ;)

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

Most designers prefer Vue nothing new here.

Thread Thread
 
devimposter1 profile image
devimposter

Not sure what you mean by this but, I have been doing full stack dev for 20 years.

Thread Thread
 
ivan_jrmc profile image
Ivan Jeremic

And 15 of them with Vue.

Thread Thread
 
devimposter1 profile image
devimposter

This doesn't even make sense... oh well

Collapse
 
swyx profile image
swyx

k

Collapse
 
elpheno profile image
Pheno • Edited

Very strange in 2020 as statement!

With svelte you can do everything you want as you can use Vue too!
Angular still in use in big companies as React as well!
What if someone throw you “Blazor” is the future???
By this I mean your preference is not an universal truth!

You limit the svelte usage to only web pages

Collapse
 
swyx profile image
Comment marked as low quality/non-constructive by the community. View Code of Conduct
swyx

try to work on your english communication skills. this is not coherent or professional.

Collapse
 
mikenikles profile image
Mike

Pheno, thanks for sharing your thoughts on this topic, I agree with you. This blog post to me looks like it's meant to create controversy and visibility for himself. He started the post by saying this is his personal opinion, so that's where I stopped reading as it is not more than that: a personal opinion of a single individual.

Also, please don't take that comment about your English skills seriously. It was unnecessary and unprofessional to make such a comment.

Collapse
 
jesseskinner profile image
Jesse Skinner • Edited

I disagree with this take. Svelte is more than capable of building any web app that React can. The ecosystem is new, yes, but it's growing quickly. The compiler is young and evolving, with lots of potential for performance to improve further. Svelte today is comparable to React in 2015. If you could travel back to the year 2015, would you tell your company to put off using React and to build all your web apps with Angular 1 or Ember?

Collapse
 
swyx profile image
swyx

I appreciate that you removed "this is a bad take" from your opener.

Collapse
 
peerreynders profile image
peerreynders • Edited

You can, of course, use React to make sites.

At this point I feel you've already lost the potentially sizeable "just pick one" crowd - "OK, React it is" - it doesn't matter how nuanced a case you make for there being "actually different jobs".

React proved Components are the right way to go.
I want to code using components

"I think Components should vanish in the same way as Frameworks."

The Real Cost of UI Components

Objects were going to be the be-all and end-all after structural programming. Where are we now? Functional programming, Data-Oriented Design (ECS), etc. Similarly "UI Components" may not be a lasting abstraction. Convenient for the time being, perhaps. Until it becomes necessary to package things at a finer level of granularity or reorganize according to a different set of concerns (I'm also partially guided by the Elm community's experience that components don't work in Elm - leading to a different approach of composition).

"What size of app are you targeting for React to be 5-13% of total JS?"

I think this has more to do with the npm "there is a dependency for that" culture - i.e. people including dependencies for a tiny fraction of the total capability - there is only so much tree-shaking can do. The Svelte community has always struck me as more lean-minded. The whole productivity centric (DX-first) culture of React encourages the use of additional dependencies without necessarily carefully considering the inevitable tradeoffs down the line (e.g. total size of the app).

The fundamental question in the industry should be "do you need an app for that"? It also needs to be questioned whether "web apps" should keep pursuing the native app experience that SPAs seek to emulate. Even back in 2015 PPK called for Web vs. native: let’s concede defeat - not to give up but so that effort could be redirected to rethink the web - i.e. to find solutions that are more in line with the capabilities and constraints of the web.

From that perspective I think Svelte is more in line with the future of the web than React - provided the web has a future.

Collapse
 
ryansolid profile image
Ryan Carniato

I love this Richard Feldman talk. I hadn't seen this before but this is the sort of thinking I've employed while working on my own UI libraries. In this video he basically recreates OOP in FP environment but that is beside the point. But it isn't about some sort of doctrined approach. He's pointing out that logical breakdown in this manner can help us keep things in our heads. I think flexibility to support this sort of cognitive modelling is essential part of scalable UI libraries. There is value upfront of identifying the build -> discover -> refactor pattern so that you can alleviate the pressure of the inevitable refactor, and not let these organizational concerns own you.

Although admittedly there is another level for people who don't even want to think about that. Like, to quote Rich Harris, "hey computer build me a website". I don't think this is a site versus app distinction but it definitely happens more in the former. Some tools are just easier to use than others. And more often than not it is intentional. If something is inherently complicated making it easy requires adding a level of complexity. When we are ready to advance our knowledge we need to unravel those constructs already made for us in the name of easiness. Whereas the simple tool never really changes just builds upon. But maybe for many things people don't ever need to get past level 1.

Collapse
 
rowemore profile image
Rowe Morehouse

Agree. I don't love writing in .jsx and I find React to have unnecessary complexity for the marketing sites I typically develop.

Collapse
 
ivan_jrmc profile image
Ivan Jeremic

What complexity, you write JS nothing else.

Collapse
 
juanfrank77 profile image
Juan F Gonzalez

Ok @swyx you had my attention before but you convinced me now. I tried Svelte before and thought it was cool but for pet projects (still have to learn React for the job tho)
But with this distinction I see it clearer now, I will reach for Svelte anytime I don't need to build a complex, interactive app and don't want to use just HTML + CSS .

Svelting all the sites!!

Collapse
 
swyx profile image
swyx

yayy!! join us!

Some comments may only be visible to logged-in visitors. Sign in to view all comments.