Skip to content

Lesson 2 of 9 · 24m

Runes Reactivity: $state, $derived, and $effect Without Superstition

Svelte 5 reactivity explained as ownership and dependency tracking — plus the effect habits that keep loops and duplicate work out.

A new hire usually meets Svelte 5 runes as syntax. Treat them instead as three different jobs: owning state, deriving state, and synchronizing with the outside world. If you keep those jobs separate, Svelte stays pleasant. Mix them, and you recreate every bad useEffect pattern in a new dialect.

$state owns mutable truth

<script>
  let filters = $state({
    query: "",
    severity: "high",
    page: 1,
  });
</script>

<input bind:value={filters.query} />
<select bind:value={filters.severity}>
  <option>high</option>
  <option>medium</option>
</select>

filters is deeply reactive as a proxied object. You can mutate filters.page += 1; you do not need immutable spread gymnastics. That does not mean mutation is free of design cost — it means Svelte does not make you pay a syntax tax for normal changes.

$derived is not cached state

<script>
  let rows = $state([]);
  let visible = $derived(rows.filter((row) => row.severity === "high"));
  let count = $derived(visible.length);
</script>

A derived value is a relationship, not a second source of truth. Do not write results back into state unless the user can edit them independently. The classic bug is copying server data into $state, editing the copy, and then wondering why refreshes either overwrite user input or never arrive.

$effect is for external synchronization

<script>
  let room = $state("ops");
  $effect(() => {
    const ws = new WebSocket(`wss://api.internal/ws/${room}`);
    return () => ws.close();
  });
</script>

Svelte tracks values read inside the effect. When room changes, the cleanup runs and the effect runs again. There is no dependency array because dependencies are observed, not declared. That also means accidental reads create accidental re-runs; structure effects narrowly.

The one rule that prevents pain

Render output should be $state plus $derived. Event handlers initiate change. $effect talks to systems outside Svelte. If an effect is only calculating data for rendering, it is almost certainly a derived value wearing a trench coat.

Field notes

  • Mutating nested arrays in $state is fine; replacing them with plain detached copies can sever the dependency you intended.
  • $effect does not run during server rendering. Browser-only APIs belong there or behind an onMount boundary.
  • When logging "effect runs too often," log which reactive values the effect reads. The dependency is in the body, not a lint rule.

Was this lesson helpful?

Sign in to rate