Svelte vs. React: Comparing JavaScript component libraries
The hype around Svelte is hard to ignore if you're following the JavaScript framework ecosystem. Svelte has garnered a devoted community that hails it as a game-changer in frontend development.Â
However, for beginners and even experienced developers, the constant emergence of new technologies and their associated hype can be overwhelming. While the technical merits of Svelte and React have been heavily debated, the practical differences between the two are often marginal.Â
What truly matters to most developers, particularly those early in their careers, is whether the technology will gain mass adoption. This is because the reasons for a technology's adoption often extend beyond its technical merits, and encompass factors such as ecosystem size, availability of libraries, developer availability, and funding.Â
In this article, I'll explore the technical merits of Svelte and React, talk briefly about their origins, and focus on the more critical factors to consider when choosing a technology. But a note before we begin: Contentful works smoothly with either framework, so regardless of which one a developer chooses, they can expect a great developer experience.
What is React?Â
React is a free and open source component-based frontend JavaScript library for declaratively building interactive user interfaces. It was launched in 2013 at Meta (formerly Facebook). Today, it is still maintained by Meta along with a community of individual developers and companies.Â
React is only concerned with state management and rendering that state to the Document Object Model (DOM). You design views for each state, and React will efficiently update and render just the right components when your data changes. These encapsulated components manage their own state and you can compose them to make complex UIs.Â
Because React is only concerned with rendering state to the DOM, it does not provide a complete application. It is designed specifically for building user interfaces and therefore does not include many of the tools necessary to build a full application. This allows the choice of whichever libraries the developer prefers to accomplish tasks such as performing network access or local data storage. Common patterns of usage have emerged as the library matures.
A central feature of React is the use of a virtual DOM. React creates an in-memory representation of the DOM that caches its state, then when changes happen, it computes the resulting differences on the virtual DOM, and then updates the browser's displayed DOM efficiently. This approach avoids the costly process of recalculating CSS styles and layout for the entire page, and only updates the subcomponents that have been changed. As a result, React can render updates to the UI in a highly efficient manner.
An important thing to note about React is that when you build a React component, you use a declarative syntax called JavaScript Syntax Extension (JSX) (this is optional and you can use pure JavaScript but I’ve never seen anyone build a React app without using JSX). JSX is an extension to the JavaScript language syntax that looks similar in appearance to HTML. This allows developers to create more intuitive and expressive code, while reducing the cognitive load required to understand the underlying logic of the components.
React also supports server-side rendering, which allows you to render your React components on the server and send the resulting HTML to the client. This can be useful for improving the performance of your application, as well as for search engine optimization (SEO) and a better user experience.
What is Svelte?
Like React, Svelte is a free and open source component-based frontend JavaScript library for declaratively building interactive user interfaces. It was launched in 2016. Today, it has two full-time maintainers and a community of individual developers and companies. Svelte also supports server-side rendering.
Unlike React, Svelte avoids the overhead associated with runtime intermediate representations, such as the virtual DOM. While in React, the browser must do extra work to convert the declarative component structures into DOM operations at runtime which eats into the frame budget and taxes the garbage collector. Svelte compiles the code at build time into highly optimized imperative client-side vanilla JavaScript that directly manipulates the DOM. Svelte does not run in the browser, which enables it to eliminate the parts of the framework that are unnecessary for your app, resulting in a smaller bundle with no external dependencies, faster initial load times, and improved performance.
This compiler approach unlocks a broad range of capabilities. Svelte uses an HTML-like syntax for describing UI which is much closer to vanilla HTML than JSX but with some syntactic sugar added for extra capabilities. Svelte components use standard CSS that is scoped to the component by default, which eliminates issues with the CSS cascade. Although global styles can still be employed, popular CSS libraries such as TailwindCSS can also be used. This simplicity makes it easy to learn, particularly for those who are already familiar with HTML and CSS. Svelte's compiler approach allows components to be written in a very concise and expressive manner while still producing very efficient applications.Â
Additionally, Svelte has great built-in support for TypeScript, which makes it easier to write type-safe, maintainable code.
Why is React so popular?
React’s popularity today has eclipsed that of all other frontend development libraries. The evidence is plain to see in the Stack Overflow Developer Survey, Jamstack Community Survey and The State of JS survey, all of them conducted and released in 2022.
Why is this? When React was released, it pulled together many good parts of existing libraries and frameworks into one package and added some technical features that were unlike anything else that existed. These factors were instrumental in its rise to the top. Here are some of those features:
Easy creation of dynamic applications: React simplifies the process of creating dynamic web applications compared to vanilla JavaScript, which can become complex quickly.
Improved performance: With the virtual DOM, React makes applications faster by updating only the items that were changed instead of updating all components, as traditional web applications did.Â
Reusable components: Components are the building blocks of any React application, with a single app often comprising multiple components. These components encapsulate their logic and controls, which can be reused throughout the application, resulting in dramatically reduced development time.
Unidirectional data flow: React follows a unidirectional data flow. This means that when designing a React app, developers often nest child components within parent components. As a result, it becomes easier to debug errors and locate where a problem occurs in an application at the moment in question.
Web and mobile app development: While React is commonly used for web applications, it can also be used to create mobile applications using a library called React Native. Since React is only concerned with creating user interfaces and not so much about the render target, that render target can be a mobile app.Â
Dedicated debugging tools: React ships a first-party browser extension that can be used to debug React applications. This makes debugging React web applications fast and easy.
The technical aspects of React have been instrumental in its rise to the top, but technical features alone aren’t enough. They can easily be replicated once they are understood, especially from a free and open source project like React. So, perhaps more important than the technical features, are the non-technical aspects. Here are some of the ones that have (and continue to) set React apart.Â
The ecosystem: I’ve already mentioned that React is only concerned with rendering UI interfaces and doesn’t provide the rest of the tools for building a complete app. The result of this is that the community has developed an enormous ecosystem of libraries and tools to extend React. You can pretty much install anything to do anything in React. Not to mention all the sub-ecosystems like NextJS, ReactQuery (TanStack Query), etc. that are building sub-ecosystems within the React ecosystem.Â
Adoption: Look at any adoption curve online on any survey for frontend UI frameworks right now, I can guarantee you that React (or some library built on React) will be at the top. Its first-mover advantage has put it so far ahead that it will be difficult to unseat.
Job market: React jobs are in demand, so new and aspiring developers learn React and increase its adoption. These are the people who will make decisions about tech stacks in their companies and they are likely to use what they have the most experience with, further driving adoption.
Cost of switching: What incentive do people have to switch to something else? Maybe some are objectively better than React but many of the benefits of competing frameworks are miniscule gains compared to the cost of switching. Maybe that’s valuable for special use cases where they’ve optimized everything else and are looking to squeeze out the remaining performance gains. For most people, React is good enough, especially when they have bigger issues to deal with.
Backing of a big tech company: React rode on the popularity and support of Meta (formerly Facebook) which drove its rapid growth. Everyone wanted to jump on the trend, and that created many React developers, which contributed to its continued popularity.
Popularity: People use React because other people use React and that virtuous cycle keeps its popularity going. Popularity has a network effect that creates more popularity.
If I had to advise a prospective frontend developer right now who wants to figure out what to learn, I’d definitely recommend React. It's popular, there are many jobs available, there's a vibrant community backing a massive ecosystem, big companies use it, and big startups are building on top of it. It’s a no-brainer. Or is it?Â
How is Svelte rocking the boat?
Okay, so React does its job, has a booming ecosystem, is widely known and loved by developers, and has great backing. Why then are we talking about Svelte?Â
Small bundle, faster apps: One of Svelte’s biggest strengths is its small JavaScript bundle sizes. Because Svelte is a compiler, you always get the minimum subset of features required by your app. For example, the Svelte implementation of the TodoMVC is 3.6kb zipped. For comparison, React plus ReactDOM with no app code is about 45kb zipped. Even if your app is only made of one component, you still have to serve the 45kb that is React itself. This makes Svelte ideal for cases where bandwidth is limited, which again makes it a perfect fit for older devices and users who might have poor internet connections. This makes up a far much bigger fraction of the world population than people inside the tech bubble often realize. Furthermore, Svelte is a good choice for any app that will be run on low-power devices that can’t parse JavaScript quickly: For example, smart TVs, watches, and other IoT devices, or lower spec smartphones.Â
Easier to learn: Svelte feels like a natural next step if you’ve been learning HTML, CSS, and JavaScript. This makes it easy to collaborate with people who have a basic understanding of CSS and HTML. If you know HTML and CSS, you can write Svelte immediately. You can then learn more as you go, layering new concepts on top of that. Sure there are still many things that aren’t vanilla HTML, but they’re easily guessable once you see them done a few times. Being close to regular ‘ole HTML also means it is a much easier on-ramp into using UI frameworks in general compared to React.
Batteries included: Unlike React, Svelte comes with many essentials included out of the box. While React has tons of external libraries to extend it, it’s nice to work with a framework where I don’t have to be making decisions at every turn about what to use. To be fair to React, there are some things React has first-party that Svelte relies on external libraries for, for example DevTools and Mobile/Native. Some examples of great Svelte built-in features include:Â
State management: Svelte stores are much simpler compared to having to use React’s context, redux, and the many react state management libraries out there. Stores are JavaScript objects that adhere to a simple interface, i.e., have a `subscribe` method that returns an unsubscribe function. They allow you to access data or functionality from multiple components. They’ll update your components whenever their data changes and they allow for separation of the state management from the component hierarchy. This is important when the same piece of data is needed in more than one place. This is how you create a Svelte store:
And this is how you read and write to it:
Reactivity: Svelte uses mutable variables for local state, and they’re reactive out of the box. This makes for leaner code. Here’s a Svelte counter component:
As you can see, this looks a lot like a regular HTML file. This, however, is also clever enough to know that whenever the value of the count variable changes, all the values that reference it should change as well. Updating a value, and all the things that depend on it, is achieved simply by using the assignment operator (=). For comparison, here’s the same thing in React:
Static Scoped Styling: Svelte offers static scoped styling, which is just CSS, with no need for CSS-in-JS solutions. By adding a style tag in the component and writing CSS, Svelte automatically scopes the CSS to the component.Â
Transitions and Animations: If you’ve never worked with animations and transitions before, don’t worry. With Svelte, you don’t have to think about much. Straight out of the box, you just slap on some pre-baked functions and it works.
Abstracting the pain: Svelte's syntax provides a pleasant developer experience by abstracting some of the pain that its predecessors had. For example, forms can be a pain in React. That’s why libraries like Formik and React Hook Form exist. A form in React would look something like this:
Whereas in Svelte, the code is more concise and easier to follow:
Interoperability: Svelte allows using npm libraries in any JavaScript technology because Svelte apps are JavaScript. In contrast, a library built with React cannot be used with Angular, for example. Even though the ecosystem of dedicated Svelte packages and plugins is relatively small, you can use any framework-agnostic package with Svelte and it can contribute to all the other ecosystems.
Using the web platform and Progressive Enhancement: Svelte encourages developers to use the web platform and follow the Progressive Enhancement design philosophy when building applications. This results in more robust apps that can still function even without JavaScript. Progressive Enhancement prioritizes core functionality and accessibility, ensuring that everyone can access content and features regardless of the technology they use. Therefore, Svelte apps are less reliant on JavaScript, making them more resilient to older browsers and slower connections.
As a relatively new framework, Svelte is currently facing some challenges. One of these challenges is a limited library ecosystem, so there are fewer options and less mature external libraries available. Depending on the specific project and team, this could be a minor inconvenience or a major obstacle to development. In addition, best practices for Svelte are still evolving, and the community's knowledge and conventions, including patterns, anti-patterns, and preferred libraries, are not yet fully established. Consequently, while Svelte is easier to learn, adopting it can be more challenging than adopting React, as Svelte users must solve problems that other communities have already established solutions for. However, as Svelte continues to gain more adoption, these issues will probably be resolved over time.
React and Svelte compared
Here’s a matrix for a quick comparison:
Criteria | Svelte | React |
---|---|---|
Bundle size | Small bundle size (ideal for low-power devices) | Larger bundle size |
Performance | Optimizes performance with less memory usage; Compiles code at build time for faster code | Uses virtual DOM for improved performance; Virtual DOM can slow performance |
Learning curve | Easy to learn and feels natural for beginners; Simpler syntax for easier learning | Steep learning curve with multiple concepts |
Components | Automatically generates highly efficient JavaScript code; Streamlined component system with less code | Reusable components for faster development; Reusable components with more code |
Debugging | Debugging can be difficult | Comes with dedicated debugging tools |
Ecosystem and adoption | Fewer external libraries; Younger framework with smaller community and ecosystem | Enormous ecosystem and high adoption rate; More mature with larger community and ecosystem |
Job market | The number of job opportunities is generally lower; However, demand is increasing, as more companies are discovering the benefits | Greater number of job opportunities; Many large companies and startups use it in their tech stacks |
Mobile app development | Does not have a mobile-specific library | Can create mobile apps with React Native |
Templates | Unique templating system that combines HTML, CSS, and JavaScript for easier understanding and use | Requires JSX, which can be challenging to work with |
So, should you use Svelte right now?
Is Svelte a good choice for your next project? The answer depends on your goals. If your priority is an easy-to-learn tool for building interactive UIs or gaining experience, Svelte is a highly regarded option. In fact, Svelte ranks second in retention, interest, usage, and awareness among frontend frameworks in the 2022 State of JavaScript survey, closely following Solid. However, if your goal is to land a job in the industry, React is the more widely used framework and offers more job opportunities.
For new startups or projects, Svelte can provide faster development and better performance, but finding developers who are experienced with it may be challenging, as its community is smaller compared to React, Vue, and Angular. However, if you are already familiar with another JavaScript framework, learning Svelte should be straightforward and vice versa.
Despite being smaller and less mature than other frameworks, Svelte is gaining popularity and is now being mentioned alongside React, Vue, and Angular. Svelte's growing community makes it a good option for early adopters who want to contribute to its ecosystem. Other frameworks are also taking cues from Svelte, leading to synergies in the communities.
The arguments against using Svelte are getting fewer. With full-time maintainers, Svelte's feature development has sped up. This is clearly reflected in SvelteKit finally going into version 1 in December 2022. This progress shows that Svelte is well on its way to becoming more mainstream.
Conclusion
While Svelte has many technical merits that make it superior to React in various ways, technical excellence alone is not enough to make a technology mainstream. Social proof, timing, and network effects are also critical factors, all of which React currently has in its favor.
In addition to the technical differences between Svelte and React, another consideration for developers is the compatibility of these libraries with other technologies. Of particular relevance here is compatibility with content management systems. Fortunately, Contentful works smoothly with either framework, so regardless of which one a developer chooses, they can expect a great developer experience.