What is Svelte?

widget

Svelte is a front-end, open-source JavaScript framework for making interactive webpages. The general concept behind Svelte is similar to pre-existing frameworks like React and Vue in that it enables developers to make web apps. However, Svelte brings several features to the table that provides developers with a unique experience.

The three main features are:

  • Less code
  • No virtual DOM
  • Truly Reactive

Less Code

Writing fewer lines of code saves time, reduces bugs, and increases readability. Svelte tries to enforce this by introducing a simple format written in TypeScript.

A typical Hello World code in Svelte would look something like this:

<script>
let name = "World"
</script>
<h1>Hello {name}!</h1>

In the code above, there is a simple <script> tag that encloses the code written in JavaScript. Below the <script> tag there is a typical HTML heading tag, <h1>, that writes “Hello” and templates the name variable.

This same code would be 30-40% bigger in React or Vue.

Svelte does not restrict the developer to only one additional top-level element. Moreover, Svelte lets you update the local state of a variable with ease by using the assignment operator (=). In React, however, users must use the useState hook, which makes the code heavier.

No Virtual DOM

In the most basic sense, the Virtual DOM is a way to update the state by comparing the snapshot of a previous tree of custom-objects with the current one. This is used in React.

widget

Svelte is a compiler, so the user does not need to load the library to the browser to run the Svelte code. Instead, a simple .js file is loaded on the page to render the app. All the object updates are made at compile time. This helps Svelte reduce the overhead generated by the virtual DOM. Moreover, not having to load the whole library reduces the size of the file significantly. This is especially beneficial for mobile devices.

Truly Reactive

Svelte surgically updates the DOM at build-time. This lets users build their application as per their requirements without caring about unnecessary overhead.

To make the user’s life even easier, Svelte incorporated reactivity into its language.

To change the state in React or Vue, the user needs to use hooks. Although hooks are a fundamental element for updating the state, they generate unnecessary work for the Garbage Collector.

A React code to update counter would look something like this:

const { count } = this.state;
this.setState({
  count: count + 1
});

Svelte, however, reduces and simplifies this 65 character code into the following 11 character code:

count += 1;

To read more about Svelte, click here.

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved