Beta Acid

introduction-to-svelte-image

An Introduction to Svelte: A Refreshing JavaScript Framework

  • Development
Marlon Ruttman-profile-picture

Marlon Ruttman

November 2, 2023 • 7 min read

In the ever-evolving world of web development, new tools and frameworks emerge like clockwork. One such innovation that has gained significant attention in recent years is Svelte. If you're already familiar with JavaScript frameworks like React, you might be curious about what makes Svelte unique and whether it's worth exploring. In this article, we'll delve into Svelte, its advantages, disadvantages, and tackle the burning question: Is Svelte really faster than React?

What is Svelte, and How Does It Differ from React?

Svelte, developed by Rich Harris, is a radical new approach to building user interfaces. Unlike traditional JavaScript frameworks, Svelte takes a different stance on how applications should be built. The most significant difference between Svelte and React is how they handle the DOM and bundle sizes.

  • Bundle Sizes: React relies on a virtual DOM to update the real DOM efficiently, which can lead to bulky bundle sizes. Svelte, on the other hand, compiles components into highly optimized JavaScript during build time. This means Svelte applications are notably smaller, making them faster to load and more efficient in terms of data transfer.

  • Developer Experience: React introduced a component-based model to the web, revolutionizing how we build web applications. However, the development process often involves writing a considerable amount of boilerplate code for state management and rendering. Svelte streamlines this process with its intuitive and elegant approach to building components. With Svelte, you write less code and achieve more, simplifying the development experience.

The Pros and Cons of Svelte

Pros:

  • No Virtual DOM: Svelte doesn't use a virtual DOM, eliminating the need for complex diffing algorithms. This translates to faster updates and reduced memory consumption, resulting in exceptional performance.
  • Less Boilerplate: Svelte significantly reduces the amount of code you need to write compared to React. This simplicity leads to cleaner, more maintainable code.
  • Truly Reactive: Svelte's reactivity system is built-in and effortless. There's no need for useState or useEffect hooks; components react to changes automatically, simplifying the development process.
  • Easier to Learn: Svelte's straightforward syntax and concepts make it easier for newcomers to grasp. If you're new to web development, Svelte offers a gentle learning curve.

Cons:

  • Smaller Ecosystem: Svelte's ecosystem is smaller than React's, which means fewer libraries, tools, and community support. You might need to build some functionality from scratch or adapt existing libraries.
  • Unique User Experience: While Svelte's approach is refreshing, it's not the industry standard. If you work on a team or with an existing codebase using React, transitioning to Svelte might pose challenges.
  • Less Libraries and Tools: React's extensive ecosystem boasts a wide range of libraries and tools for various use cases. Svelte, being relatively new, has a limited selection of these resources.

Is Svelte Really Faster than React?

Now, let's tackle the million-dollar question: Is Svelte faster than React? There are several compelling reasons why Svelte is often considered more performant:

  • No Virtual DOM Diffing: Svelte's absence of a virtual DOM means it doesn't need to diff and patch the DOM, resulting in faster updates.

  • Built-in Shared State: Svelte offers built-in and highly efficient solutions for shared state management, eliminating the need for external libraries or complex setups.

  • Lightweight: Svelte is approximately five times smaller than React in terms of bundle size. This translates to faster load times and a more responsive user experience.

  • Reactive by default: Svelte's reactivity system is inherent, so you don't need to implement hooks like useState and useEffect, reducing the codebase and improving performance.

Code examples

The code below is enough to have a Hello World. Zero boilerplate.

<h1>Hello world!</h1>

Defining a state variable and manipulating it with a click on a button.

<script>
  let count = 0;
</script>

<button on:click={() => count++}>Counter is {count}</button>

With the $: keyword, you can define reactive statements. They work exactly like the useEffect hook in React, but there's no need to import and declare hooks, neither defining an array of dependencies.

<script>
  let count = 0;
  $: doubled = `Counter doubled is: ${count * 2}`;
</script>

<p>Counter is {count}</p>
<p>{doubled}</p>
<button on:click={() => count++}>Increase counter</button>

This is how you loop through an array. The each block resembles a vanilla foreach, with the addition of the key extractor for each item in parenthesis.

<script>
  const items = [
    {id: 1, name: "foo"},
    {id: 2, name: "bar"},
    {id: 3, name: "baz"},
  ];
</script>

{#each items as item (item.id)}
  <p>{item.name}</p>
{/each}

Example of conditional logic. It's noticeable that Svelte uses a more verbose and explicit way that can be strange at a first glance, but it's more readable than nested ternary operators.

<script>
  let count = 0;
</script>

<button on:click={() => count++}>Counter value: {count}</button>
{#if count > 10}
  <p>big</p>
{:else if count > 5}
  <p>medium</p>
{:else}
  <p>small</p>
{/if}

Example of props declaration. Every variable that is preceded by an "export" statement is considered as a prop.

<script>
  export let color;
</script>

<p>You picked: {color}</p>

Here we import the component above and declare it passing the "color" prop.

<script>
  import Nested from './Color.svelte';
</script>

<Nested color="white" />

Slots and named slots are a way to pass children to a component. To pass one or more children, you should declare at least one slot on your component. The named slots are used to have more control over placement.

<div class="card">
  <header>
    <slot name="telephone" />
    <slot name="company" />
  </header>
  
  <slot />
		
  <footer>
    <slot name="address" />
  </footer>
</div>

Here's the import of the Card component, followed by it's declaration.

<script>
  import Card from './Card.svelte';
</script>

<main>
  <Card>
    <span>Patrick BATEMAN</span>
    <span>Vice President</span>

    <span slot="telephone">212 555 6342</span>

    <span slot="company">
      Pierce &amp; Pierce
	<small>Mergers and Aquisitions</small>
    </span>
		
    <span slot="address">358 Exchange Place, New York, N.Y. 100099 fax 212 555 6390 telex 10 4534</span>
  </Card>
</main>

And this is the final result:

introduction-to-svelte1.png
introduction-to-svelte1.png

In conclusion, Svelte's unique approach to web development makes it an attractive choice for many developers, particularly those concerned with performance and bundle sizes. While it may not replace React in every scenario, Svelte's innovative design, faster loading times, and efficient reactivity system make it a compelling option for modern web development projects

Learning Resources

You can refer to the official website to see the docs and a great tutorial section, where you can learn about all Svelte features.

Svelte has its web framework: SvelteKit. It's a fully fledged framework with the same capabilities as NextJS.

If you like benchmarks, here you can see Svelte compared with its competitors.

On the Svelte Society channel on Youtube there's a lot of webinars, tutorials and announcements. It's the best resource to keep informed about Svelte news.