Reactive Statements in Svelte

By

Learn how to derive values and run side effects when Svelte state changes, using $state, $derived, and $effect in Svelte 5.

~~~

Svelte 5 uses runes to declare state and react to changes.

Start with a state variable:

<script>
  let count = $state(0)
</script>

<button onclick={() => count += 1}>
  {count}
</button>

Calculate a value with $derived

Use $derived when one value depends on another:

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

<button onclick={() => count += 1}>
  {count}
</button>

<p>Double: {double}</p>

Svelte recalculates double when count changes.

Use $derived for values you can calculate from state. You do not need an effect for this.

Run a side effect with $effect

Use $effect when a change must affect something outside the calculation, such as logging or a browser API:

<script>
  let count = $state(0)

  $effect(() => {
    console.log(`The count is ${count}`)
  })
</script>

Svelte tracks the reactive values read inside the effect. The effect runs again when one of them changes.

Effects only run in the browser. Avoid using them when $derived can express the same relationship.

The old $: syntax

Svelte 3 and 4 used reactive statements prefixed with $::

<script>
  let count = 0
  $: double = count * 2
</script>

This syntax still works in Svelte 5 legacy mode. Use $derived and $effect in new components.

Tagged: Svelte ยท All topics
~~~

Related posts about svelte: