iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

$derived

The \$derived rune declares a value computed from other reactive state. The compiler tracks dependencies automatically; recomputes on dependency change; cached otherwise — like Vue’s computed, but Svelte-native.

derived, derived.by, fine-grained tracking

EXAMPLE
<script>
    let count = $state(0);
    let user  = $state({ first: 'Ada', last: 'Lovelace' });

    // 1) Simple derived — expression
    let double  = $derived(count * 2);
    let triple  = $derived(count * 3);
    let fullName = $derived(`${user.first} ${user.last}`);

    // 2) Multi-line derivation — use derived.by
    let summary = $derived.by(() => {
        const total = count * 100;
        const tax   = total * 0.1;
        return { total, tax, grand: total + tax };
    });

    // 3) Filtered derived
    let todos = $state([
        { id: 1, title: 'A', done: false },
        { id: 2, title: 'B', done: true  },
    ]);
    let activeCount = $derived(todos.filter(t => !t.done).length);
    let sortedTodos = $derived([...todos].sort((a, b) => a.title.localeCompare(b.title)));

    // 4) Chain — derived can read other derived
    let activeTitles = $derived(todos.filter(t => !t.done).map(t => t.title));
    let activeJoined = $derived(activeTitles.join(', '));

    // 5) Cached — only recomputes on dependency change
    let expensive = $derived.by(() => {
        console.log('recomputing…');
        return heavyFn(todos);
    });

    // 6) Cannot mutate inside a derived — side effects belong in $effect.

    // 7) Compare to Svelte 4 — $: was reactive but only worked in .svelte files
    // Svelte 4: let count = 0; $: double = count * 2;
    // Svelte 5: let count = $state(0); let double = $derived(count * 2);

    // 8) Works in .svelte.js too — extract reactive logic from components
    // counter.svelte.js
    //   export function createCounter() {
    //       let n = $state(0);
    //       let double = $derived(n * 2);
    //       return {
    //           get count() { return n; },
    //           get double() { return double; },
    //           inc() { n++; },
    //       };
    //   }
</script>

<button onclick={() => count++}>+1</button>
<p>{count} → {double} → {triple}</p>
<p>{fullName}</p>
<p>Active: {activeCount}</p>
<p>{summary.grand.toFixed(2)}</p>

Why it matters

Reach for \$derived any time you’d be tempted to write the same computation inline twice. Cached, dependency-tracked, and the compiler does all the bookkeeping — including across .svelte.js module boundaries.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
let count = $state(0);
let doubled = $derived(count * 2);
Try it Yourself »

Exercise

Derive a computed value (Svelte 5).

let double = (() => count * 2);

Discussion

Loading…