Reactive Declarations — Svelte

let total = $derived(price * portions) uses the $derived rune (a special Svelte 5 word) to make a derived value, meaning a value calculated from other values…

In the Svelte Reactivity lesson, let total = cart.length was computed only once, when the component was created. The cart grows, but the total stays the same. What you need is a formula that updates by itself, like the total column in the cashier's spreadsheet at Mrs. Sri's stall. That column holds =price*portions. The moment the portion count changes, the total changes too, with nobody redoing it on a calculator.

In Svelte 5, a formula that updates by itself is written with the $derived rune: let total = $derived(price * portions). Every time a state that the formula reads changes, Svelte computes the value again. If you have used Vue, its role is close to computed. This lesson's name, reactive declaration, comes from Svelte 4, which wrote formulas like this with a special label. That old form is covered in the Older code section below.

A value that follows: $derived(price * portions)

With $derived, a derived value (a value calculated from other values), such as the total, always changes along with its source:

<script>
  let price = 5
  let portions = $state(1)
  let total = $derived(price * portions)
</script>

<button onclick={() => portions += 1}>+1 Iced Tea</button>
<p>Total: ${total.toFixed(2)}</p>
Event portions total Shown
Start 1 5 Total: $5.00
Click +1 Iced Tea 2 10 Total: $10.00
Click again 3 15 Total: $15.00

A formula that needs more than one line is written with $derived.by. Inside it goes a function that returns the value:

let label = $derived.by(() => {
  if (portions >= 5) return "Big order"
  return "Regular order"
})

What the compiler does

Svelte 5.16 turns the +1 Iced Tea button component above into JavaScript. These are the parts that matter, taken from the compiled output:

var on_click = (_, portions) => $.set(portions, $.get(portions) + 1);

let price = 5;
let portions = $.state(1);
let total = $.derived(() => price * $.get(portions));

$.template_effect(() => $.set_text(text, `Total: $${$.get(total).toFixed(2) ?? ''}`));

In Svelte 5.57, the click handler is no longer a separate var on_click. It is written directly inside $.delegated('click', ...). $.state, $.get, $.set and $.template_effect stay the same.

Exercise: doubled from count

This lesson's exercise uses the same pattern, with smaller numbers:

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

<p>{count} x 2 = {doubled}</p>

The page shows 2 x 2 = 4. If count is later given the value 7, doubled becomes 14 on its own, without you writing doubled = 14 anywhere.

$effect to run code

Sometimes you don't need a new value, but you want to run something every time state changes, such as writing a log (a message in the console). That's the job of $effect:

<script>
  let portions = $state(1)

  $effect(() => {
    console.log("portions now:", portions)
  })

  $effect(() => {
    if (portions > 5) {
      console.log("Big order!")
    }
  })
</script>

<button onclick={() => portions += 1}>+1 Iced Tea</button>

What the console shows after the page opens and portions goes up twice:

portions now: 1
portions now: 2
portions now: 3

What's tracked: the state that is read

Now the total is computed through a function:

<script>
  let price = 5
  let portions = $state(1)

  function calcTotal() {
    return price * portions
  }

  let total = $derived(calcTotal())
</script>

Take a guess first: the markup is the same as in the first example, and the +1 Iced Tea button is clicked twice. Does the page show Total: $15.00, or does it stay at Total: $5.00?

It shows Total: $15.00. Svelte 5 doesn't look at the names written in the $derived line to find the dependencies. It records the state that is actually read while the formula runs, including state read inside a function. calcTotal() reads portions, so total depends on portions, even though the word portions isn't written inside $derived(...).

What can't be recorded is a plain variable. If portions isn't wrapped in $state, its changes aren't recorded:

let price = 5
let portions = 1                        // forgot $state
let total = $derived(price * portions)  // stays 5

Clicking the button does change portions, but total is never computed again, and the page stays at Total: $5.00. Everything that can change and is used in a formula must be $state.

📌 The order of $derived values

$derived values may depend on each other, like spreadsheet columns that use other columns:

let total = $derived(price * portions)
let discount = $derived(total >= 20 ? 2 : 0)
let toPay = $derived(total - discount)

total >= 20 ? 2 : 0 means a discount of 2 when the total is at least 20, and 0 when it is less. When portions becomes 4: total 20, discount 2, amount to pay 18. toPay is never computed from an old total. When toPay is read, Svelte first checks whether total and discount are stale, then computes the stale ones again before computing toPay. Still write total first and then the lines that use it, so the code is easy to read.

Older code: $:

In tutorials and repos written for Svelte 4, you will find $::

<script>
  let price = 5
  let portions = 1
  $: total = price * portions
  $: console.log("portions now:", portions)
</script>

⚠️ Why won't the total go up?

TL;DR: let total = $derived(price * portions) uses the $derived rune (a special Svelte 5 word) to make a derived value, meaning a value calculated from other values. Every time a state (data made with $state) that the formula reads changes, that value is computed again. Svelte records the state actually read while the formula runs, including inside a function. So $derived(calcTotal()) does follow when that function reads state, while a plain let variable isn't tracked. A formula of several lines uses $derived.by(() => { ... }). $effect(() => { ... }) runs code after the component appears, then every time state it reads changes. Use $effect for side effects (work other than calculating a value) such as logging. One $derived value may use another, and Svelte always computes it from the latest values. Change the source (the state the formula reads), not the $derived value. The exercise editor (Svelte 5.16) refuses a direct change, and since Svelte 5.25 such a change only lasts until a source changes. The exercise: let count = $state(2), let doubled = $derived(count * 2), <p>{count} x 2 = {doubled}</p> shows 2 x 2 = 4.

⚡ A formula that follows by itself

Write:

<script>
  let price = 5
  let portions = $state(1)
  let total = $derived(price * portions)
</script>

<button onclick={() => portions += 1}>+1 Iced Tea</button>
<p>Total: ${total.toFixed(2)}</p>

Meaning: $derived is a rune (a special Svelte 5 word) that holds the formula for a derived value, meaning a value calculated from other values. portions is made with $state, so portions is state (data that Svelte watches). Every time portions gets a new value, total is computed again before the page is updated. You never write total = ... yourself.

⚡ What's recorded: the state that is read

Write:

function calcTotal() {
  return price * portions
}

let total = $derived(calcTotal())
Guess first: price and portions are the same as in the first step, and the +1 Iced Tea button is clicked twice. Does it show Total: $15.00, or stay at Total: $5.00?

Total: $15.00. Svelte 5 records the state actually read while the formula runs, including inside a function. calcTotal() reads portions, so total follows.

Meaning: A plain variable (without $state) can't be recorded. So everything that can change and is used in a formula must be $state.

⚡ $effect to run code

Write:

$effect(() => {
  console.log("portions now:", portions)
})

Meaning: $effect runs once after the component appears, then again every time state it reads changes, here portions. Use $effect for side effects, meaning work other than calculating a value, such as logging. To compute a value, use $derived.

What you will learn