#svelte #javascript #frontend

Day 2: Reactivity with Runes

Welcome to Day 2. Today we learn the heart of Svelte 5: Runes.

In older versions of Svelte, let count = 0 was reactive. This was “magic” but confusing outside of .svelte files. Svelte 5 introduces explicit reactivity markers called Runes.

1. $state

The $state rune creates a reactive value.

<script lang="ts">
  let count = $state(0);

  function increment() {
    count += 1; // It's just a variable!
  }
</script>

<button onclick={increment}>
  Clicks: {count}
</button>

Wait, onclick? Svelte 5 encourages standard HTML attributes. No more on:click (though it still works for now).

Deep Reactivity

$state creates a deeply reactive proxy. You don’t need to reassign objects to trigger updates.

let user = $state({ name: "Jack", age: 30 });

function birthday() {
  user.age += 1; // Works fine!
}

2. $derived

Often you need a value that depends on others (like computed in Vue).

<script lang="ts">
  let count = $state(0);
  let double = $derived(count * 2);
</script>

$derived values are automatically updated when their dependencies change. They are read-only.

3. $inspect

Debugging reactivity can be tricky. Use $inspect (dev-only) to log whenever a signal changes.

<script>
  let count = $state(0);
  $inspect(count); // logical equivalent of console.log but reactive
</script>

Challenge for Day 2

  1. Create a width and height state (default 10 and 20).
  2. Create a derived area (width * height).
  3. Add two buttons to increase width and height.
  4. Display: “Values: {width} x {height} = {area}”.

Solution:

<script lang="ts">
  let width = $state(10);
  let height = $state(20);
  let area = $derived(width * height);
</script>

<p>Values: {width} x {height} = {area}</p>

<button onclick={() => width++}>Increase Width</button>
<button onclick={() => height++}>Increase Height</button>

You are now controlling state explicitly. Tomorrow, we learn how to control the HTML structure based on that state.