The $derived Rune
Computed values
Section titled “Computed values”$derived declares a value computed from other reactive values. It recomputes automatically whenever any value it reads changes — and it is cached, so it only recomputes when a dependency actually changed.
<script> let count = $state(2); let double = $derived(count * 2); // 4, and stays in sync let label = $derived(`count is ${count}`);</script>
<p>{double} — {label}</p>You never list dependencies. The compiler sees that double reads count and rebuilds double exactly when count changes. Derived values are read-only — you don’t assign to them; they are a function of their inputs.
Complex logic: $derived.by
Section titled “Complex logic: $derived.by”$derived(expr) takes a single expression. When the computation needs multiple statements — a loop, a temporary variable, a branch — use $derived.by with a function that returns the value.
<script> let numbers = $state([1, 2, 3, 4]);
let stats = $derived.by(() => { let sum = 0; for (const n of numbers) sum += n; return { sum, avg: sum / numbers.length }; });</script>
<p>sum {stats.sum}, avg {stats.avg}</p>$derived(x) is just shorthand for $derived.by(() => x). Dependencies are still tracked automatically — anything the function reads becomes a dependency.
flowchart LR a["$state count"] --> d["$derived double = count * 2"] b["$state numbers"] --> e["$derived.by stats"] d --> ui["DOM updates when inputs change"] e --> ui
Derive, do not sync with an effect
Section titled “Derive, do not sync with an effect”A common React-brain mistake is to compute a value in an effect and write it into state:
<script> let count = $state(2); let double = $state(0);
// ❌ Don't do this — an effect that mirrors derived state. $effect(() => { double = count * 2; });</script>This is worse in every way: an extra state variable, an extra update cycle, a chance for double to be briefly out of sync, and harder-to-follow data flow. The right tool is $derived:
<script> let count = $state(2); let double = $derived(count * 2); // ✅ one source of truth, always in sync</script>Rule of thumb: if a value can be computed from other state, derive it — don’t store it and sync it. Reach for $effect only for genuine side effects (the next lesson), not for computing values.