An Introduction to Svelte

Author:

Dominik Röschke

Svelte is both a UI Framework and a compiler. It’s not all that new, the first version (0.0.1) was released in 2016. The real breakthrough for it was its current version, Svelte 3 (released 2019).

Svelte and the Svelte Community likes to compare it to React, which is why I will do the same in this blog post. Compared to React, Svelte adoption is very much in the early stages: 370.000 Weekly downloads compared to the 17.000.000 of React!

There’s lots of cool things about it that should lead to more adoption over time though!

A very simple Svelte Component

This is an example of a very simple Svelte component. It exposes a property called number and renders it in a paragraph containing the text “The number <property value> has been passed as a property”.
If the prop that was passed is 5, the span containing the property will have the css class “red” applied to it.

You can play around with it here.

Automatically scoped styles

Unlike React where you have to either configure CSS modules or integrate one of the many CSS in JS libraries, Styles written in a Svelte component are automatically scoped to that component.

You can play around with the example here.

Actual reactivity

A variable is automatically reactive in Svelte. That means the page content will automatically change if you assign a variable to it, unlike in React where you have to use useState or similar mechanics.

Svelte:
React:

Additionally, 2 way binding to a variable is easily possible without a library, no onChange event handler required.

Svelte
React:

The best part about Sveltes reactivity though is its surgical precision when state updates.

In React, both console.log calls will always fire, when either count or name are updated, unless you wrap it in useEffect with a dependency array. Sveltes compiler automatically detects which statements have to be re-run when state changes and only executes these statements.

You can play around with the example here.

Integrated Transitions

Animations on transitions are integrated directly into Svelte. If an element should fade in when it is rendered, all it needs is the in:fade attribute as part of it’s html tag. This can be customized with an optional duration. A fade out effect can be added independently: out:fade=”{{duration: 200}}” adds a fade-out effect when the element is removed from the DOM that lasts for 200 milliseconds.

You can play around with the example here.

Animating an element when it is conditionally rendered in React is a lot harder and requires an additional library and component wrapper in the form of CSSTransition (or a similar library).

Integrated Animations

Even animations are integrated into Svelte, making reordering a table a joy to watch, which you can do here.

An animation showing how re-sorting a table looks in Svelte

Animating a table on sort is even more of a joy to code than to watch, since it only requires a single attribute to work!

All that is necessary for the animation is the animate:flip attribute which can be further customized by adding the “{{delay: 100, duration: 1000}}” value to the attribute.

The Svelte compiler will handle the rest and play the animation when the order of elements changes. It is important, that a keyed each is used to build the <tr> elements, so that Svelte can identify each element and determine which element moved where.
This is achieved by providing (row.number) as the key value in the each block in the example.

Integrated Statehandling

Statehandling is a very contentious topic in the world of React, with a load of different libraries that address it: Redux, Zustand, Recoil, MobX, Overmind, …
To be totally fair to React, it’s done a lot to improve statehandling without libraries in recent releases and useReducer is a joy to use.

Svelte makes the whole conversation a lot easier by providing a solution to handle global state by default: Stores!

Store definition:



		
Store Usage:

In addition to the writable store used in the example here, there’s also readable and derived Stores. Readable stores can’t be changed from the outside, while derived stores take one or multiple stores and calculate a value out of them.

In case of the example, the Svelte compiler knows that the $-prefix in front of a variable means that the store value should be accessed. The compiler will automatically handle subscribing to the store when the component is created and unsubscribing when it is destroyed to avoid memory leaks.

Since it is a writeable store, a new value can be assigned to it and all subscribers will be updated to the new value.

Excellent Developer Experience

Svelte is not a framework like React, instead it’s a compiler that works like a framework. This brings a couple of great things for developer and user experience. On the user side it means smaller JavaScript bundles since only the parts of the framework that are needed are compiled into the JavaScript for the component.

On the developer side it means things like integrated A11y-Warnings during development and in the build logs if, for example, an <img>-Tag is missing an alt-Attribute for visually impaired people or aria-element-attributes are misused.

Svelte is very easy to learn since it doesn’t introduce many new abstractions and methods if you’re already familiar with HTML, CSS and JavaScript.
In addition to being easy to pick up, Svelte also has very expressive errors that tell you what you did wrong right in the browser. That’s only in development mode, of course!

Additionally, the vite-plugin-svelte already has svelte-inspector integrated into it, which means that you can press a key combination in your browser to get a special cursor that allows you to click any Svelte element. On click, it will open the respective Svelte Component file in your IDE of choice and scroll you to the line that corresponds to the element you just clicked.

In future versions this may be expanded to be able to just open an inline editor based on the popular CodeMirror library, that allows you to edit your Svelte files right in your browser. Still without any browser plugin being required!

Vite-plugin-svelte also guarantees incredibly quick hot module reload speeds thanks to the excellent tooling of Vite.

In the next blog post we are going to take a look at how SvelteKit, the official meta framework of Svelte, makes developing an app with Svelte even easier and more fun.

Want to give it a try?

The Svelte Maintainers are currently working on a new set of tutorials for both Svelte and SvelteKit that you can find on learn.svelte.dev .

[/vc_section ]