Nefe James Nefe is a frontend developer who enjoys learning new things and sharing his knowledge with others.

Should you switch from React to Svelte?

5 min read 1478

Svelte and React logos.

Editor’s note: This article was last updated on 16 March 2022 to reflect the most recent releases of React and Svelte.

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 2021 developer survey has React in the number one spot for web frameworks), Svelte has much to offer, and 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 overwhelming presence in the frontend community.

Contents

React’s virtual DOM vs. Svelte’s compiler

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

Ease of use

If you’re deciding between learning React or Svelte, the ease of use of these two frameworks is an important factor to consider.

While more widely used, learning React 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:

<style>
  h1 {
    color: green;
  }
</style>

<script>
  let name = 'Nefe';
</script>

<h1>Hello, {name}!</h1>

Developer experience

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 React, { useState } from 'react';

export default () => {
  const [a, setA] = useState(1);
  const [b, setB] = useState(2);

  function handleChangeA(event) {
    setA(+event.target.value);
  }
  function handleChangeB(event) {
    setB(+event.target.value);
  }

  return (
    <div>
      <input type="number" value={a} onChange={handleChangeA}/>
      <input type="number" value={b} onChange={handleChangeB}/>
      <p>{a} + {b} = {a + b}</p>
    </div>
  );
};

Spacing included, Svelte is nine lines of code, while React is 21. That is a significant difference! The beautiful thing about the Svelte app is that 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.



Svelte also comes with built-in effects and animations. You don’t need to use a third-party library to create animations like you would in React. svelte/motion, svelte/transition, svelte/animate, and svelte/easing provide us with powerful modules to create amazing animations out of the box. Amazingly, these built–in effects won’t increase the size of your app.

With Svelte, you don’t have to worry about writing unique classes, or styles leaking out of their components; styles are component-scoped in their style tags, which allows for flexible styling.

All of these benefits in Svelte mean less of a headache for you, the developer, by making your work easier. It also means you don’t need to learn how to use styling libraries like Styled-Components and Emotion. As a result, you can write and ship code faster, because there’s less technological overhead.

Server-side rendering

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 with 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 83.3k GitHub stars, and SvelteKit has 7.5k stars. Next has a more active developer community, which means more templates, resources, courses, and articles.

Performance

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:

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

Developer popularity

React is still the most popular web framework. However, this survey was not limited to frontend frameworks, and included frameworks like ASP.NET, Ruby on Rails, Laravel and more.

According to a State of JS 2021 survey, Svelte has a higher level of satisfaction among developers. 90 percent of developers are satisfied with Svelte, and 84 percent are satisfied with React. In this same survey, Svelte was voted the most loved framework.

Bundle size

Another cool 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.

The gzipped version of Svelte is 1.6KB, while React gzipped is 42.2KB (with ReactDOM included).

Conclusion

The Svelte ecosystem is developing rapidly. With the introduction of Sapper, 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 interesting of developers year after year. With Rich Harris moving to Vercel, Svelte now has the funding and community backing of the Vercel ecosystem, and is set up for ambitious levels of growth with this new development. There has never been a better time to pay more attention to Svelte.

LogRocket: Full visibility into your production React apps

Debugging React applications can be difficult, especially when users experience issues that are hard to reproduce. If you’re interested in monitoring and tracking Redux state, automatically surfacing JavaScript errors, and tracking slow network requests and component load time, try LogRocket.

LogRocket combines session replay, product analytics, and error tracking – empowering software teams to create the ideal web and mobile product experience. What does that mean for you?

Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay problems as if they happened in your own browser to quickly understand what went wrong.

No more noisy alerting. Smart error tracking lets you triage and categorize issues, then learns from this. Get notified of impactful user issues, not false positives. Less alerts, way more useful signal.

The LogRocket Redux middleware package adds an extra layer of visibility into your user sessions. LogRocket logs all actions and state from your Redux stores.

Modernize how you debug your React apps — .

Nefe James Nefe is a frontend developer who enjoys learning new things and sharing his knowledge with others.

Leave a Reply