Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 35 ยท Reactivity with Runes

Derived Values with $derived

Compute values from state with the $derived rune in Svelte 5, use $derived.by for longer logic, and avoid the effect-for-everything trap.

Often one value follows from another: a total from a list of prices, a filtered list from a search box, a "can submit" flag from form fields. In Svelte 5 you express that relationship with $derived. A derived value recomputes automatically when the state it read changes, and it is never stale.

The basics

SVELTE
<script>
  let width = $state(4);
  let height = $state(3);
  let area = $derived(width * height);
</script>

<input type="number" bind:value={width} />
<input type="number" bind:value={height} />
<p>{width} x {height} = {area}</p>

$derived(expression) takes an expression, not a function. Svelte notes which state values the expression reads and recomputes only when one of them changes. You cannot assign to a derived value directly (area = 5 is an error), because its value is defined by the expression.

Derived values are lazy and cached: the expression reruns only if something it read has changed, and only when something actually needs the value.

Longer logic with $derived.by

For anything that needs statements (loops, if chains, local variables), use $derived.by with a function:

SVELTE
<script>
  let numbers = $state([3, 8, 1, 9]);

  let stats = $derived.by(() => {
    if (numbers.length === 0) return { min: null, max: null, mean: null };
    const min = Math.min(...numbers);
    const max = Math.max(...numbers);
    const mean = numbers.reduce((a, b) => a + b, 0) / numbers.length;
    return { min, max, mean };
  });
</script>

<p>min {stats.min}, max {stats.max}, mean {stats.mean}</p>
<button onclick={() => numbers.push(Math.round(Math.random() * 10))}>Add</button>

$derived(expr) is shorthand for $derived.by(() => expr).

What counts as a dependency

Any state value read while the expression runs becomes a dependency, even inside functions you call from it:

SVELTE
<script>
  let items = $state([{ price: 5, qty: 2 }, { price: 3, qty: 1 }]);

  function lineTotal(item) {
    return item.price * item.qty;
  }

  let total = $derived(items.reduce((sum, i) => sum + lineTotal(i), 0));
</script>

Because lineTotal reads price and qty on a reactive proxy, changing items[0].qty updates total.

Values read after an await or inside a callback that runs later are not tracked, since the tracking only covers synchronous reads during the computation.

Derived instead of effect

A frequent beginner mistake is to keep a second state variable in sync with an effect:

SVELTE
<script>
  let count = $state(0);
  let doubled = $state(0);

  // Avoid: extra state, extra work, easy to get out of order
  $effect(() => {
    doubled = count * 2;
  });
</script>

Prefer:

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

The derived version is shorter, cannot be out of sync, and does not run any code unless it is needed. Effects (next lesson) are for side effects like logging and talking to the outside world, not for computing values.

Overriding a derived value

Since Svelte 5.25, you may temporarily assign to a derived value, which is handy for optimistic UI (for example showing a "liked" state at once, before the server replies). The next time its dependencies change, it goes back to being computed. Use this sparingly; most code never needs it.

Stand-in: derived values

This stand-in computes derived values lazily with a dirty flag. It is not Svelte's implementation, but it shows the key behaviors: caching, and recomputing only after a dependency changes.

JS Lazy cached derived value (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The "recomputing" line appears twice in total, even though get was called four times.

Total from a list (stand-in page)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does $derived take as its argument?

    $derived(expr) takes an expression. Use $derived.by(() => ...) when you need a function body.
  2. 2. Which is the better way to keep doubled in sync with count?

    $derived is the tool for computed values: no extra state, cannot go stale.
  3. 3. What happens if a derived expression reads state after an await?

    Dependencies are collected during the synchronous run of the expression.
  4. 4. When should you use $derived.by?

    $derived.by takes a function so you can write multi-statement logic.

Summary

  • $derived(expr) computes a value from state; it is cached and always current.
  • Use $derived.by(fn) for multi-statement computations.
  • Dependencies are whatever state is read synchronously during the computation.
  • Prefer $derived over an $effect that writes state.

Next: Side Effects with $effect