DEV Community

Marco Monsanto
Marco Monsanto

Posted on

Svelte: An introduction

Svelte is one in a sea of frameworks and libraries to build User Interfaces.

Even if most, if not all of them follow the same principle of creating components that are readable, reusable and composable to build dynamic and complex layouts, there are always differences in the inner works and syntax.

In this post, I will share how is the syntax, how reactivity works in Svelte, and what ends up in the bundle after the build process. For that, I will create a Simple Counter with increment and decrement.

First, The Syntax

This is all the code that we need for creating our counter, update the value and render the new value.

Code Snippet from Simple Counter

The Script

The script tag is where we add all our javascript to manipulate our component.

In this case, we only manipulate the value of the count variable.

The Styles

The style script is where we add all our styles for this component. All styles inside the component will be scoped to itself, so even if you add styles to

, it will only apply in the

's inside itself by adding a class with "svelte-component_generated_hash".


The rest of our code will be seen as HTML.

In the end, we will have something like this as our DOM.

HTML Snippet of the browser

As you can see, we have a super clean DOM with all our declared HTML and scoped styles.

How can we achieve reactivity in Svelte

Reactivity is the process that triggers the rendering process for the DOM to reflect the changes in our variables values.

Reactivity in Svelte works based on assignments, in our case we have a variable that we want to change based on clicks in the increment and decrement buttons.

Now let's take a look at our "script" tag.

Script snippet from Simple Counter

We have:

  • One variable called count
  • Two functions called increment and decrement

Both of our functions perform an assignment in our count variable. This will do trigger a re-render and update the DOM with our new value.

Here is the documentation related to reactivity:

To change component state and trigger a re-render, just assign to a locally declared variable.
Update expressions (count += 1) and property assignments (obj.x = y) have the same effect. - Svelte Docs

What's Next

After this, we will move into more real live use cases like communication between components with props and events.

I will be posting more content related to Svelte and how to work with it in the next weeks, feel free to follow me here and in my twitter.

Thanks for reading this blog post, I hope that I could explain in an easy way this introduction to Svelte.

Top comments (0)