loading...
Cover image for Svelte for Sites, React for Apps

Svelte for Sites, React for Apps

swyx profile image shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Originally published at swyx.io ใƒปUpdated on ใƒป14 min read

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.

Discussion

pic
Editor guide
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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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.

Thread Thread
jfbrennan profile image
Jordan Brennan

React's ecosystem is not a benefit. It's a dumb necessity grown from the need to create more stuff, much of it being React-only versions of existing stuff, because React is so incompatible and fussy.

Thread Thread
renanmouraf profile image
Renan Moura

This! I only see the truth in this statement.

Collapse
ascotto profile image
Andrea Di Minico

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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 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
ajcwebdev profile image
anthonyCampolo

React also has significantly more developed meta-frameworks.

Thread Thread
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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

Collapse
trashandfire profile image
trash-and-fire

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
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

(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

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
Collapse
jfbrennan profile image
Jordan Brennan

I wouldn't want to change your mind - you have freed yourself my friend! Welcome to the other side :)

Collapse
codechips profile image
Ilia Mikhailov

Not sure what side you are referring to, but thanks. I took the path of least resistance ๐Ÿคทโ€โ™‚๏ธ

Thread Thread
jfbrennan profile image
Jordan Brennan

Everyone in front-end has to go through React at some point, but not everyone makes it through to the other side, i.e. the latter end of the React experience where you've realized it's a total pain and there's many smaller, easier, more enjoyable options out there.

Thread Thread
codechips profile image
Ilia Mikhailov

Totally agree. However, it requires courage and an open mind. Also helps if you've been in the game for some time too. Herd mentality and FOMO are strong. You are running in the opposite direction than everyone else and that can be scary.

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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

Thread Thread
ryansolid profile image
Ryan Carniato

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 lose 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
jfbrennan profile image
Jordan Brennan

React was good for awhile, but there are just so many smaller, faster, easier options today. What really kills me though is React (and its ecosystem) trying to get credit for "solving" the very problems it creates.

There's this growing React echo chamber in the frontend community and its not healthy (e.g. components are a very old pattern and many devs knew components were "the right way" to build web apps long before React existed).

Collapse
ivanjeremic profile image
Ivan Jeremic

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
ivanjeremic 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
ivanjeremic 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
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
ivanjeremic profile image
Ivan Jeremic

What complexity, you write JS nothing else.

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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
elpheno profile image
Pheno

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
Info Comment marked as low quality/non-constructive by the community. View code of conduct
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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

Collapse
mikenikles profile image
Mike Nikles

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
peerreynders profile image
peerreynders

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
lepinekong profile image
lepinekong

I believe Svelte within a few years (4 years on average like for node ? ) may be able to be a serious contender to React but I don't believe most developers and companies will be happy to invest in both as It takes investments to do so. So they'd rather play with it until svelte takes over a good chunk of the market before they do the switch.

Collapse
jesseskinner profile image
Jesse Skinner

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
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

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

Collapse
xyn profile image
Mydrax

React was never meant to be a framework/library that a new developer should start with but herd mentality more or less drives them to do so. "Its built by facebook and there's tons of jobs" is enough to convince a lot of people.

While I do understand that particular fact, I don't think a sufficiently experienced developer will have alot of trouble learning React. Because of the aforementioned issue, there's a lot of free and high quality learning material.

Svelte will not replace React, and in time will introduce its own problems. I am a React early-adopter and I was literally thrilled when it came out, I felt the same way I did about JQuery at the time that most do about React when compared to Web Components or X framework/library (ex: Svelte). Now I see that there are problems that React itself introduces.

Hooks hell, using hooks the right way, state management etc. all have solutions but the problem is that its a problem in the first place.

I'm not trying to be critical about anything but I don't believe that the problem lies in React but the way we solve the problem as a whole.

This will however always be a problem that will not be solved perfectly.

So what do we do? Use whatever that attempts to solve the problem the most elegantly. But with the understanding that it will never be solved fully. ex: You can use React for a simple site but should you?

PS: I enjoyed reading this post very much!

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
Collapse
lepinekong profile image
lepinekong

I often agree with you on many things you say but since I practice First Principles myself - I've been trained with a friend of Deming who advocates to do so and he goes well beyond with what he called SOPK (System Of Profound Knowledge) - but I think your "First Principles Thinking" may be misleading : for complex systems you cannot deduct everything from just facts and logics rules, Deming insists (as well as others like the great scientist Henri Poincarรฉ in his writing "Science and Hypothesis") that you always have a THEORY behind and that Science is about EXPERIMENTING to make your theory WRONG so as to ADJUST it. So he invented for non-scientific people his Deming wheel or PDSA : Plan Do Study Act (which is the true essence of Kanban - Toyota created Kanban to win the prestigious Deming prize after WWII)

And since you mention epistemology indeed Deming learned with Walter Shewhart who wrote a book on the subject as he was worried about the way statistics are misapplied in the real world including by scientists as they think that math + datas alone equates science which is wrong and that can lead to biases (like in pharmaceutical industry where studies show that many "scientific" studies made by corporations are 4 times more positively conclusive than by public laboratories).

epistemology

In software it's even worse as no stats are not even involved but opinions : there are many cults under the guise of "best practices" which people follow blindly or even by social pressure (which is weird in a technical field) see for example overreacted.io/the-wet-codebase/ or interest in disguise (for example Hรฅkon Wium Lie being accused of abusing his position in w3c according to this article polylogue.org/#:~:text=Paged.js%20...)

Collapse
urielbitton profile image
Uriel Bitton

Nice article! I love react and use it on all app dev, i would occasionally use it for websites but mostly personal ones, for clients, they usually prefer wordpress and its tough to integrate react with wordpress!

Collapse
unicorns profile image
Unicorns

I think you have it reversed, it's not just about shipping less code, it's about shipping performant code. Web apps require more re-renders than sites, the more re-renders you have the more performance cost React increases.

On a side note, it's troubling to see how "write once, ship anywhere" development is increasing non-performant apps on mobile & desktop. Majority of them are electron or built on something similar.

Collapse
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

react prioritizes correctness over performance. performance is not everything.

Collapse
unicorns profile image
Unicorns

So do every other popular framework, not sure what your point is there. Performance is the major factor for apps & websites.

Not hating on React, Vue or Angular but it's time to move on or change the internals. They have popularized component based development. Backbone, underscore and friends did it before them but when React & others came into existence, everyone noticed the benefits and made the switch. Now, we have better frameworks & tools than React, Vue, Angular, etc so it's time to move on and adapt those. In future, if something better than svelte comes up then as a web community we should promote them.

Faster, performant & accessible web is what we should push towards.

Collapse
adityapadhikbl profile image
Aditya Padhi

Nice Article @swyx .
I am also experimenting with Svelte. I came across few scenarios like graphql support, UI components for rapid development etc.

If we have support for these then I think it will be more fun to develop apps with Svelte.

Collapse
weakish profile image
Jang Rush

Nice comparison! I want to translate it to Chinese. Can you give me the permission to so?

Collapse
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

please go ahead let me know when you're done and I can link you!

Collapse
weakish profile image
Jang Rush

Just finished and published the Chinese translation at the weekend: nextfe.com/svelte-for-sites-react-... There is a back link to swyx.io/svelte-sites-react-apps/ at the beginning of the translated text.
P.S. During translation, I noticed that "hundreds more" was linked to github.com/sveltejs/community/tree..., which is 404 now. I changed it to github.com/sveltejs/community/tree... in the translated text.

Thread Thread
swyx profile image
Thread Thread
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

wowww thank you very much! and i have linked back to you from the top of my article. so glad you enjoyed it and hope it reaches my fellow Chinese devs!

Collapse
alekseiberezkin profile image
Aleksei Berezkin

How Svelte is different from all others templating engines like Angular, Vue and Ember? Why people are so excited about it? Just another HTML with loops and conditionals.

Collapse
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

i don't have the energy to get into this. you can make up your own mind, I don't need to convince you.

Collapse
alekseiberezkin profile image
Aleksei Berezkin

My apologies if it sounded like a trolling, I'm not here to mock anything. I heavily use React in production, however I'm open to new things. There was some hype about Vue, I wanted to try it, but now it seems Svelte is in trend. I watched a couple of tutorials but can't decide. Perhaps I just don't see something important? I'd be glad to change my mind.

Thread Thread
pavelloz profile image
Paweล‚ Kowalski

Good point of start is looking up Youtube: RIch Harris. He has 2 presentations about the differences. At least thats how i got into it. One is with "Reactivity" in the title, the other one i dont remember, but there are only couple anyways :)

Thread Thread
peerreynders profile image
peerreynders

Rich Harris - Rethinking reactivity
The Return of 'Write Less, Do More' by Rich Harris

Virtual DOM is pure overhead

To me Svelte feels more like a logical extension to the technologies of the web platform (though there is always room for improvement) while React exists in it's own universe.

For some perspective this might be useful: The Real Cost of UI Components

Collapse
andrewbaisden profile image
Andrew Baisden

As good as Svelte is it still needs to gain more adoption before it is truly accepted outside of developer circles. Still not many commercial jobs available for it outside of personal projects. And I'm betting many companies and recruiters have never even heard of Svelte. It took a while for Vue to gain awareness.

Collapse
kokizzu profile image
Kiswono Prayogo

SvelteNative~

Collapse
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

do you understand the difference between NativeScript and React Native's approach?

Collapse
kokizzu profile image
Kiswono Prayogo

yes i prefer nativescript approach

Collapse
rfinner profile image
Rob Finneran

I would enjoy reading your explanation of the differences between NativeScript and React Native's approach. Thanks!

Thread Thread
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

I can't because I've never used NativeScript lol. I just suspect that most pple are giving svelte native too much credit for what it is

Collapse
phantas0s profile image
Matthieu Cneude

To me, the real question is: was it more "difficult" to build an app before React or Svelte? jQuery wasn't that good, for sure, but I mean I saw frontend developers using vanilla JavaScript with great success for apps and websites.

I still wonder if focusing on the tool is the good idea. Not that many people care about that, at the end.

Collapse
ajcwebdev profile image
anthonyCampolo

So you're saying Svelte should conquer the Jamstack?

Collapse
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

idk about conquer but i do think more people should try it as it is a great fit for the Jamstack

Collapse
victoredier profile image
Victor Edier

Why don't you just use HTML as programming language?????

Joking please don't kill me

Collapse
catalinradoi profile image
CatalinRadoi

ASP.NET MVC FTW

Collapse
kuncevic profile image
Aliaksei Kunceviฤ

I am using Angular for building SPA's and I am using Angular (Universal Prerender) for building my static sites, am I guilty? ๐Ÿ˜€ ๐Ÿค”

Collapse
swyx profile image
shawn swyx wang ๐Ÿ‡ธ๐Ÿ‡ฌ Author

do what makes you happy man life is short