Editor’s note: This article was last updated by Carlos Mucuho on 17 April 2023 to add information about third party support with React vs. Svelte. For more on Svelte, check out our post on how to build a simple Svelte app.
React and Svelte are two frontend JavaScript frameworks that provide developers with a productive approach to building web applications. While React is often seen as the automatic choice for frontend devs (Stack Overflow’s 2022 developer survey has React in the No. 1 spot for web frameworks), Svelte has much to offer, and it shouldn’t be overlooked.
In this article, we’ll look at the main differences between React and Svelte, and review some of the strengths Svelte brings to the table that may be overshadowed by React’s presence in the frontend community.
Jump ahead:
React uses a virtual DOM to interpret the application code during runtime. It bundles a specific amount of overhead code, which will run in the browser’s JavaScript engine to monitor and update the DOM. The virtual DOM watches for any changes and calculates the best possible method to make these changes to the real DOM.
Svelte is a compiler that translates applications into JavaScript code. This ensures that when your program is running in the DOM, no overhead framework code is injected into the browser.
At build time, Svelte translates the components into a highly efficient imperative code that updates the DOM surgically. Svelte has demonstrated that you can achieve exceptional performance without the virtual DOM, so they decided to get rid of it. Because all your Svelte code is compiled down to minimal JavaScript before it ever gets to the browser, you’re able to write highly performant code.
If you’re deciding between learning React or Svelte, the ease of use of these two frameworks is an important factor to consider. While React is more widely used, learning the framework can be daunting when you have to learn things like JSX and CSS-in-JS to build even the most basic applications.
Compared to React, Svelte is simpler to understand and get started with, because the major portion of Svelte is plain JavaScript, HTML, and CSS. Svelte also sticks closely to JavaScript’s classic web development models, and introduces only a few extensions to HTML, making it much easier to learn.
To demonstrate, here’s an example of a Svelte component. All we have here is basic HTML, CSS, and JavaScript:
<script> let name = 'Nefe'; </script> <h1>Hello, {name}!</h1> <style> h1 { color: green; } </style>
While less code doesn’t always mean better, more functional code (a strong point for Svelte) means less time writing code in Svelte than in React. Let’s look at a demonstration.
Here’s a sample of a basic application made with Svelte:
<script> let a = 1; let b = 2; </script> <input type="number" bind:value={a}> <input type="number" bind:value={b}> <p>{a} + {b} = {a + b}</p>
Below is a code snippet from the same application built with React:
import { useState } from 'react'; export default () => { const [a, setA] = useState(1); const [b, setB] = useState(2); function handleChange (event, setValue) { const { value } = event.target; setValue(value); }; return ( <div> <input type="number" value={a} onChange={(e) => handleChange(e, setA)} /> <input type="number" value={b} onChange={(e) => handleChange(e, setB)} /> <p>{a} + {b} = { parseInt(a) + parseInt(b) } </p> </div> ); }
Spacing included, Svelte is eight lines of code, while React is 19. That is a significant difference! The beautiful thing about the Svelte app is, although it uses less code, it is in no way less functional.
Additionally, with Svelte, you don’t need to worry about forgetting to export components, as they are exported by default, and ready to be imported by other components. With React, you have to do that manually.
Server-side rendering (SSR) is an application’s ability to convert HTML files on the server into a fully rendered HTML page for the browser. The server sends fully rendered HTML, CSS, and JavaScript to the client when a user requests a page.
SSR comes with several advantages, such as faster initial page load time and better SEO. Also, SSR pages are optimal for users with a slow internet connection, because they can see the rendered HTML while the JavaScript is processing. In this particular comparison, React may be the winner because it has Next.js, the most popular framework for creating SSR applications.
In Svelte, there’s SvelteKit. SvelteKit is a full-stack Svelte framework for building websites with Svelte. Like Next, SvelteKit comes with features such as routing, layouts, API endpoints, static site generation, server-side rendering, and more.
While Next and SvelteKit have similarities, there are also distinct differences, one of them being how they handle images. Next’s Image
component makes working with images a dream for developers. We no longer have to worry about compressing and optimizing images ourselves; Next handles them for us.
Another advantage Next has over SvelteKit is popularity and community. Next has 105k GitHub stars, and SvelteKit has 14.2k stars. Next has a more active developer community, which means there are more templates, resources, courses, and articles to use for your project.
When you run the production build of a Svelte app, Svelte compiles your code to highly-optimized vanilla JavaScript. This means that no framework code is added at runtime, which improves the application’s overall performance because the browser has less work to do.
Svelte surgically updates the DOM without relying on a middleman or any complex reconciliation techniques. Svelte’s compiler tracks changes in your variables and updates the HTML accordingly. It looks through your code and watches for components that depend on your variables, then updates those components as the variables change. This way, Svelte is reactive without having to rely on a third-party API.
On the other hand, by calling this.state
or using the useState
Hook, React must be told to watch for modifications. Let’s take a look at the following Svelte code:
<script> let count = 0; $: doubled = count * 2; function handleClick() { count += 1; } </script> <button on:click="{handleClick}">Click me!</button> <p>{count} doubled is {doubled}</p>
Here, we have a variable count
, and another doubled
. doubled
depends on count
for its value. If we were to update doubled
, in React, we have to write setDoubled(count)
.
However, the JavaScript identifier $:
tells Svelte that doubled
is a variable that depends on count
, and Svelte knows to automatically update doubled
whenever count
changes. For a more in-depth look at reactivity, check out Ovie Okeh’s article.
Svelte is a framework that comes with most of the essential features needed to create modern web applications natively. Unlike React, Svelte provides out-of-the-box support for animations and transitions, as well as built-in component styling capabilities.
In React, developers often rely on third-party libraries such as React Transition Group or Framer Motion to add animations and transitions to their components. In contrast, Svelte has a built-in transition system that makes it easy to add animations and transitions to any element or component.
Here is an example of how to use the built-in transition system in Svelte:
<script> import { fade } from "svelte/transition"; let visible = true; </script> <button on:click={() => (visible = !visible)}> {visible ? "Hide" : "Show"} </button> {#if visible} <div transition:fade> <p>Hello world!</p> </div> {/if} <style> div { margin-top: 10px; background-color: #1a1a1a; padding: 1rem; border-radius: 0.25rem; } </style>
In the code above, a simple fade transition is applied to the div
element using the transition:fade
directive. When the button is clicked, the visible
variable is toggled, causing the div
element to appear or disappear with a fade effect.
React’s default behavior is to apply CSS globally, which can lead to collisions when the same className
is used for multiple elements. To avoid this issue and scope CSS to a specific component, developers often use techniques such as inline styling, CSS modules, and third-party libraries, such as styled-components.
In contrast, in Svelte, styles are defined within the component itself and are automatically scoped to that component, preventing style collisions and making it easy to maintain the codebase.
Here is an example of how to define styles in a Svelte component:
<script> export let name = "John"; </script> <h1>Hello {name}!</h1> <style> h1 { color: #333; } </style>
In the code above, the h1
element is styled with a color of #333
using the style block. Because the style block is defined within the component, the styles are automatically scoped to that component.
Svelte’s built-in features are a big benefit for developers. They can focus on building their applications instead of laying the groundwork and minimizing the time and effort required to develop apps.
Another great thing about Svelte is that its bundle size leaves a far smaller footprint than that of React. This makes a huge difference performance-wise, especially in low-powered devices or CPU-intensive applications. Svelte also has a smaller bundle size when gzipped.
According to the website bundlephobia, the minified and gzipped version of Svelte (version 3.58.0) is 1.8 KB, while React and ReactDOM (version 18.2.0) gzipped is 44.5 KB.
React is still the most popular web framework. According to the State of JS 2022 survey, Svelte has a higher level of satisfaction among developers. 89.7 percent of developers are satisfied with Svelte, and 83 percent are satisfied with React. In Stack Overflow’s 2022 developer survey, Svelte was voted the second most loved framework in a list including all programming languages while React was voted sixth.
In order to decide when to switch from React to Svelte, you need need to consider the project requirements, the team’s preferences, and experience. If performance and bundle size are the main concerns, Svelte’s built-in functionality and compile-time approach can make it a better choice than React, which primarily depends on third-party libraries. If the team is more focused o n developing small to medium-sized apps, Svelte’s simpler syntax and user-friendliness can help to speed up and enhance development efficiency.
Furthermore, if the team has previous web development experience but is unfamiliar with React’s syntax and concepts, Svelte’s syntax may be easier to comprehend and work with, making it an excellent alternative for new projects.
The Svelte ecosystem is developing rapidly, with the introduction of SvelteKit, which is Svelte’s version of Next.js, and Svelte Native for building native mobile applications. It is clear that Svelte continues to pique the interest of developers year after year.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowIn this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.
Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]
Generate OpenAPI API clients in Angular to speed up frontend development, reduce errors, and ensure consistency with this hands-on guide.
Making carousels can be time-consuming, but it doesn’t have to be. Learn how to use React Snap Carousel to simplify the process.