Lesson 5 / 25
$derived
Values computed from other state.
Declarative derived values
let total = $derived(price * quantity) recalculates when any state it reads changes. The expression should be free of side effects. For logic that needs several statements, use $derived.by(() => { ... return value; }). Dependencies are tracked automatically from whatever is read synchronously during evaluation, and derived values are recomputed lazily when read after a change. Svelte 4 used reactive statements such as $: total = price * quantity, which were tracked by the compiler only at the top level of a component; runes also work inside functions, classes and .svelte.ts modules.
Derived totals and filters
Cart summary.
<script lang="ts">
let items = $state([
{ name: 'Keyboard', price: 49, qty: 1 },
{ name: 'Mouse', price: 19, qty: 2 }
]);
let query = $state('');
let total = $derived(items.reduce((sum, i) => sum + i.price * i.qty, 0));
let visible = $derived.by(() => {
const q = query.trim().toLowerCase();
if (!q) return items;
return items.filter((i) => i.name.toLowerCase().includes(q));
});
</script>
<input placeholder="Filter" bind:value={query} />
{#each visible as item}
<p>{item.name} x {item.qty}</p>
{/each}
<p>Total: {total}</p>A spreadsheet formula
A $derived value is like a cell containing =B1*C1: you never set it by hand, it simply reflects the cells it references.
Quick check: When should you use $derived.by instead of $derived?
- When the value must be writable from outside
- When the computation needs several statements
- When the value should never update
- When you need to run a side effect
Answer
When the computation needs several statements — $derived.by takes a function body.