In the era of artificial intelligence, I’m going through Svelte basics! It’s been a while since I used Svelte, and it’s been a long while since I last read through tutorial for a language framework. This feels good, I am enjoying it!

Here are some things that I wanted to take a note of:

Mutation-compatible reactivity

When I was using React years ago, I often wrote updates like:

data = [...data, newData];

instead of:

data.push(newData);

This is because React promotes immutable states. Rather than modifying an existing array, you create a new one and pass it to the state setter. Since the new array has a different reference, React can easily determine that the state has changed and trigger a re-render.

Svelte takes a different approach.

Its runes-based reactivity system uses JavaScript Proxy objects under the hood, and can detect internal changes (mutations). So operations like

data.push(newData);

can be reactive without requiring JS kung-fu, which is arugably a better developer experience.

One small nuance: Svelte 5’s mutation tracking applies to values created with $state(...).

Keyed-each blocks

This one was a bit tricky. Basically when we use each block to list someList, there is a list of components rendered. Then if we modify someList, in a way that it affects the order of the list, then it can cause issues because Svelte links each rendered component with the index of the items in the list. Namely, if we remove the first element of someList, then 0-th rendered component will now match with the 0th data of the new array.

To prevent this, we need a better way to map rendered data and someList, and that’s when we use the keyed each block notations:

{#each things as thing (thing.id)}
	<Thing name={thing.name} />
{/each}

Minor points

  • $effect() rune – it could return a function, which will be run when the effect runs next time.
  • The file some.svelte is a component, meaning it is meant to include html, css, js. If you only want a reusable Svelte code (say some shared rune), you can use some.svelte.js, which will then go through the svelte compiler, before going to js runtime.
  • props flow down, events/callbacks flow up.

Finished going through ‘basic svelte’, except the transition part.