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 |
portionschanges every time the button is clicked, soportionsis made with$state.pricenever changes, so a plainletis enough.$derived(...)holds the formula. Svelte records which state is read while that formula runs. Here it is onlyportions, soportionsis called the dependency oftotal, meaning the source thattotalfollows.- Every time
portionsgets a new value,totalis computed again before the page is updated. You never writetotal = ...yourself. - Without
$derived,let total = price * portionsis computed once and stays at$5.00however many portions are added. The compiler also warns:State referenced in its own scope will never update. That is the text from Svelte 5.16 in the exercise editor. Svelte 5.57 gives the same warning,state_referenced_locally, asThis reference only captures the initial value of `portions`. Did you mean to reference it inside a closure instead?
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) ?? ''}`));
$.state(1)makes a box for a value that records which code reads it.$.get(portions)reads what's inside,$.set(portions, ...)replaces it.$derivedbecomes$.derived(() => ...): the formula is wrapped in a function so it can run again. While that function runs, the$.get(portions)inside it records thattotaldepends onportions.- Clicking the button runs
$.set(portions, ...). Svelte markstotalas stale (it needs computing again), then runs thetemplate_effectthat readstotalagain. Inside thattemplate_effect,totalis computed again, and the<p>'s text is replaced. pricestays a plainletand is read without$.get, becausepriceisn't state.
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
$effectruns once after the component appears on the page, then again every time state it reads changes.- Its dependencies are recorded the same way as for
$derived. The second$effectreadsportionsin theifcondition, so that$effectruns every timeportionschanges. But it only printsBig order!onceportionsis more than 5. - Use
$effectfor side effects, meaning work other than calculating a value, such as logging or saving tolocalStorage. To compute a value, use$derived; don't fill a variable from inside$effect.
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>
$: total = formulais the same aslet total = $derived(formula).$:in front of an ordinary statement (console.log,$: if (...) { ... }, a block$: { ... }) is the same as$effect(() => { ... }).$:is a JavaScript label (a rarely used marker for a line) that Svelte 4 gave a new meaning. Svelte 4 only tracked the names written directly in that line. So$: total = calcTotal()ran only once, and older code often writescalcTotal(price, portions)so thatpriceandportionsare written in that line and get tracked. Svelte 4 also put$:lines in order by itself.- In a component that uses runes, the compiler refuses
$::`$:` is not allowed in runes mode, use `$derived` or `$effect` instead.
⚠️ Why won't the total go up?
let doubled = count * 2without$derived. The value is computed once and never changes again. In the exercise, the checker (the program that checks your answer) also looks for$derived(in your code.- A source that isn't
$state. A plainlet portions = 1can be changed by a handler, but its changes aren't recorded, so$deriveddoesn't compute again. Writelet portions = $state(1). - Changing the result instead of the source. In the exercise editor (Svelte 5.16), the compiler refuses
total = 0in a handler:Cannot assign to derived state. Since Svelte 5.25 that line is allowed, but the result is temporary: as soon asportionschanges,totalis computed again and the0is gone. So still changeportions, and lettotalbe computed.
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.