Chapter 5: Reactive State

Svelte implements reactivity at compile time by instrumenting variable assignments. Knowing how assignment triggers updates—and how to derive values with $:—prevents subtle stale-UI bugs with arrays and objects.

Declaring Reactive Variables

Any top-level let variable referenced in a Svelte template is reactive: reassigning it with =, +=, or ++ schedules a batched DOM update for only the expressions that depend on it. Because Svelte tracks assignments rather than object mutations, calling items.push(x) alone will not trigger an update unless you reassign items = [...items, x] (or items = items):

<script>
  let count = 0;
  let history = [];

  function increment() {
    count += 1;
    // Reassign the array reference so Svelte detects the update
    history = [...history, count];
  }
</script>

<p>Count: {count} (steps: {history.length})</p>
<button type="button" on:click={increment}>Increment</button>

Reactive Declarations

When one value depends on another, storing both independently risks letting them drift out of sync. Prefixing an assignment with Svelte's $: reactive label tells the compiler to recompute that variable automatically whenever any value read on its right-hand side changes:

<script>
  let count = 0;

  // Svelte declares and updates `doubled` automatically whenever `count` changes
  $: doubled = count * 2;
</script>

<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button type="button" on:click={() => count++}>Increment</button>

Reactive declarations are topologically ordered by the compiler, meaning $: quadrupled = doubled * 2 will always evaluate after doubled regardless of line order in <script>.

Reactive Statements

You can also attach $: to an if block or a multi-line block $: { ... } to run side effects—such as logging, persisting drafts to localStorage, or clamping out-of-range inputs—whenever referenced state updates. Keep reactive blocks focused and avoid mutating a variable inside a statement that also reads it, which can cause infinite update loops:

<script>
  let count = 0;
  let warning = '';

  $: if (count > 10) {
    warning = 'Threshold exceeded: consider resetting.';
  } else {
    warning = '';
  }
</script>

Computed Properties

Derived values like full names, filtered lists, and cart totals should always be computed with $: rather than duplicated in manual event handlers. Because Svelte evaluates $: statements only when their dependencies actually change, derived lists stay fast and consistent:

<script>
  let firstName = 'Ada';
  let lastName = 'Lovelace';
  let query = '';
  let tasks = ['Write tests', 'Review PR', 'Deploy build'];

  $: fullName = `${firstName} ${lastName}`.trim();
  $: visibleTasks = tasks.filter(t => t.toLowerCase().includes(query.toLowerCase()));
</script>

<p>Owner: {fullName} ({visibleTasks.length} matching tasks)</p>

Practice: Build a reactive shopping cart component with an items array, add/remove handlers using immutable array reassignment, and $: declarations for subtotal, tax, and total.