4 Reasons to Learn Svelte in 2022

Written byKalanKalan
💡

If you have any questions or feedback, pleasefill out this form

This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.

1. Growing Popularity

According to the State of JS survey, Svelte was included in the questionnaire options for the first time in 2019, achieving an impressive satisfaction rate of 88% (React 89%, Vue 87%). This year, Svelte's satisfaction rate rose to 89%, making it the top-rated front-end framework.

Screenshot_2021-02-09 State of JS 2020 Front-end Frameworks

Additionally, its usage rate in 2019 was at 8%, ranking sixth, but in 2020 it jumped to 15%, placing it fourth. This indicates that more and more developers are paying attention to this front-end framework.

Screenshot_2021-02-09 State of JS 2020 Front-end Frameworks(1)

2. Low Barrier to Entry, Easy to Learn

Svelte’s syntax is almost entirely compatible with HTML, and template syntax such as {#if} and {#each} is straightforward for those familiar with .ejs or .pug. The design of Svelte's syntax aims to reduce the cognitive load, allowing beginners to quickly grasp the basics and start coding. A Svelte component looks like this:

<script>
  export let prop; // Declare prop like this
  let count = 1; // Declare a variable like this
  onMount(() => { // Lifecycle method
    count++; // Changing the variable value will trigger a component update
  })
</script>

<style>
  p { font-size: 14px }
</style>

<!-- Wrap variables in {} -->
<p>{count}</p> 

<!-- Pass attributes -->
<Component count={count} />

There's no need to learn additional concepts like hooks to understand the component layout easily. Svelte also includes a hashing mechanism during compilation for styling, so there's no worry about CSS naming conflicts. All of this is built into Svelte's implementation, meaning there's no need for extra loaders (like css-modules) to handle styles.

For those primarily focused on backend development who suddenly need to create front-end pages, Svelte is an incredibly accessible and efficient tool for rapid development.

3. Small Bundle Size

Compared to React and Vue, Svelte compiles code before generating it, allowing for various optimizations and dependency tracking during the compilation phase. Interested readers can check out the author’s article “Virtual DOM is pure overhead,” which discusses how avoiding direct manipulation of the DOM API to achieve a declarative effect inevitably requires some performance trade-offs. For instance, React uses the Virtual DOM and diffing mechanisms. To keep the diff cost manageable and cross-platform compatible, React needs a lighter mechanism to describe the render tree — the Virtual DOM.

In large applications, if performance issues arise, React offers various optimization mechanisms, such as the useMemo and shouldComponentUpdate APIs, allowing developers to fine-tune performance.

Svelte does not use a Virtual DOM; the essential dependency tracking mechanism is analyzed during the static phase, resulting in a significantly smaller runtime bundle size compared to React and Vue. This means that in medium to small applications, Svelte often boasts a smaller bundle size and better performance.

4. Built-in Transition and Animation Mechanisms

Svelte has built-in transition features that integrate seamlessly with common scenarios in development. In fact, Svelte offers built-in transition mechanisms that allow you to use the transition directive for achieving transition effects. Svelte will determine the appropriate moments to execute transitions (for entering and exiting elements).

In Svelte, you can write:

<script>
  import { scale } from "svelte/transition";
  import { onMount } from "svelte";

  let toggle = false;

  onMount(() => {
    setInterval(() => {
      toggle = !toggle;
    }, 2000);
  });
</script>

<main>
  {#if toggle}
    <h1 transition:scale>Hello World</h1>
  {/if}
</main>

When {#if toggle} is true, the h1 will render (entering), and when false, it will be removed (exiting). With transition:scale, Svelte executes the transition at the right moments.

In React, you typically need to use react-transition-group; otherwise, writing toggle && <Component /> would directly unmount the component when toggle is false, preventing the transition from executing properly. Alternatively, you could use react-spring for more advanced animations.

Vue developers might think this is not particularly impressive, as Vue also has a built-in transition mechanism that executes corresponding transitions under v-if conditions. However, the difference is that Vue requires you to define class names and implement transitions in CSS, while Svelte allows you to do so declaratively without having to define class names in CSS separately.

"After all, it’s just modifying inline styles directly with JavaScript, which is a poor-performing approach."

In reality, Svelte dynamically generates CSS keyframes, and the underlying code for the animation is as follows:

function go() {
  const {
    delay = 0,
    duration = 300,
    easing = linear,
    tick = noop,
    css
  } = config || null_transition;

  if (css) animation_name = create_rule(node, 0, 1, duration, delay, easing, css, uid++);
  ...
}

Here, create_rule is the core of the transition mechanism, implemented through stylesheet.insertRule. For example, if I define a transition like this:

function myTransition(node) {
  return {
    css: t => `
      transform: scale(${1 - t});
    `;
  }
}

It will generate an animation keyframe (through insertRule):

@keyframes svelte_hash_animation_name {
  0% {
    transform: scale(0);
  }
  
  10% {
    transform: scale(0.1);
  }
  
  20% {
    transform: scale(0.2);
  }
  
  30% {
    transform: scale(0.3);
  }
  ...
}

This is then added to the DOM node that will execute the animation, avoiding unnecessary performance costs from modifying inline styles every frame.

Crossfade and FLIP Effects Easily Implemented

Using examples can make things clearer; please click the button on the page to see the effect in action:

When clicked, the tag transitions from its current position to its destination position, smoothly settling into the final position. This effect can be easily achieved with Svelte, and when you click on a tag, you'll notice that other tag positions transition as well, making the interaction feel more fluid. This technique, known as FLIP, is also implemented in Svelte.

Drawbacks

After discussing the advantages, let's combine our experiences to address some of the drawbacks.

1. Too Much Compilation Time Processing

For instance, Svelte performs dependency tracking during the static phase, which can make debugging a bit challenging if you want to inspect the generated code for any oddities that may need adjustment.

Additionally, while this may not be an issue for developers familiar with HTML, newcomers might find Svelte components look similar to HTML but have distinct differences, such as the {} syntax and reactive variables, which could lead to confusion.

The requirement for Svelte to be precompiled means it cannot import libraries directly in the <script> tag like Vue; instead, tools like Vite or Webpack are needed for execution.

2. Must Conform to Svelte's Component Format

To create Svelte components, you must write them according to Svelte's component structure. In contrast, in React, all components are JavaScript files, meaning any valid JavaScript can be used to write React components.

3. Relatively Fewer Resources Compared to Other Front-End Frameworks; Ecosystem Still Developing

Although resources for Svelte have been increasing recently, they are still largely in English, and resources in Chinese remain relatively scarce. This can make it harder to find solutions when issues arise, and the available solutions are not as comprehensive as those for other front-end frameworks. This is something that will take time to improve or can be addressed by collaboratively creating more Svelte-related resources!

4. Still Low Usage Rate

For most companies, Svelte's usage rate is still low, which may not make it the best choice for job seekers.

Conclusion

Svelte has carved out a distinct niche compared to other front-end frameworks, with its concise syntax, compilation philosophy, write-less-code approach, and small bundle size gaining attention in recent years. I personally appreciate this diversity; while not everyone may prefer it, the clash of ideas can lead to greater progress and even spark inspiration. As we approach the new year in 2021, why not set aside your familiar front-end frameworks for a moment and give Svelte, the top-rated framework of 2020, a try?

If you're interested in Svelte, feel free to check out some of my past articles:

If you found this article helpful, please consider buying me a coffee ☕ It'll make my ordinary day shine ✨

Buy me a coffee