Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 35 ยท Reactivity with Runes

Reactive State with $state

Learn the $state rune in Svelte 5: declaring reactive variables, updating them, objects and arrays, class fields, and common mistakes.

State is data that changes over time and that the page should reflect. In Svelte 5 you declare it with the $state rune. There is no setter function and no wrapper object: a state variable is an ordinary variable, and assigning to it updates everything that reads it.

Declaring and updating state

SVELTE
<script>
  let count = $state(0);
  let name = $state('Ada');
  let done = $state(false);
</script>

<button onclick={() => count++}>Clicked {count} times</button>
<input bind:value={name} />
<label>
  <input type="checkbox" bind:checked={done} />
  Done
</label>
<p>{name}, done: {done}</p>

Any assignment form works: count = 5, count += 1, count++. The compiler rewrites these so that the places in the markup that read count are scheduled for an update.

Updates are batched: if you change three values in one function, the DOM updates once afterwards, not three times.

State flow

Event Click or input
Assignment count += 1
Update Readers rerun, DOM changes
1 / 2

Objects and arrays are deeply reactive

If you pass an object or array to $state, Svelte wraps it in a proxy. Changes to its properties and array contents are tracked automatically:

SVELTE
<script>
  let todo = $state({ text: 'Write notes', done: false });
  let items = $state(['milk', 'eggs']);

  function add() {
    items.push('bread'); // works: no need to reassign
  }
</script>

<label>
  <input type="checkbox" bind:checked={todo.done} />
  {todo.text}
</label>
<button onclick={add}>Add</button>
<ul>
  {#each items as item}<li>{item}</li>{/each}
</ul>

This is a major simplification over older Svelte, where items.push(x) did nothing until you wrote items = items. Deep reactivity is the topic of Deep Reactivity and Snapshots.

State only counts where you declare it

$state makes the variable reactive. Copying its value into something else creates an ordinary value:

SVELTE
<script>
  let count = $state(0);
  let snapshot = count; // plain number copy, not reactive
  count = 10;           // snapshot is still 0
</script>

If you need a value that follows another one, use $derived (next lesson), not a copy.

The compiler warns (state_referenced_locally) when you read a state value in a position where it will not stay up to date, such as an initial value of another variable. Treat that warning seriously.

Class fields

Classes can hold reactive fields. Use $state on a field declaration (or in the constructor):

JavaScript
// counter.svelte.js
export class Counter {
  count = $state(0);

  increment() {
    this.count += 1;
  }
}
SVELTE
<script>
  import { Counter } from './counter.svelte.js';
  const counter = new Counter();
</script>

<button onclick={() => counter.increment()}>{counter.count}</button>

Note the file name: runes work in modules only when the name ends in .svelte.js or .svelte.ts. Also notice onclick={() => counter.increment()}: passing counter.increment directly would lose this. Wrap it in an arrow function or define the method as an arrow-function field.

Stand-in: state that notifies readers

The stand-in below implements a state holder for a plain object. It records which "readers" asked for which key and reruns only those when a key changes. It is much simpler than Svelte's real proxy implementation, but shows why todo.done = true can update the page without any setter call.

JS Proxy-based reactive object (stand-in)

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

No output.

Both effects ran once at the start. Afterwards each assignment reran only the effect that had read that key.

Common mistakes

  1. Forgetting $state: let count = 0 is a plain variable. Changing it does not update the page. (Svelte 4 treated top-level let as reactive; Svelte 5 does not.)
  2. Destructuring loses reactivity: let { done } = todo; copies the boolean. Read todo.done where you need it.
  3. Replacing instead of mutating when sharing: if a child holds items, mutate or reassign consistently so everyone sees the same object.
  4. Using $state outside the right files: it must be in .svelte, .svelte.js or .svelte.ts.

Try it in a page

This runnable page mimics a counter and a toggle, the first exercise most people write. The code you would write in Svelte is in the comments.

Counter and toggle (stand-in)

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does assigning to a $state variable do?

    Assignments to state are tracked; readers are scheduled to update, and updates are batched.
  2. 2. Is items.push('x') enough to update the page if items = $state([])?

    Svelte 5 wraps objects and arrays in proxies, so mutation methods are tracked.
  3. 3. What is the value of snapshot after: let count = $state(0); let snapshot = count; count = 10;

    Copying a primitive creates a plain value; it does not follow later changes.
  4. 4. In which file names can class fields use $state?

    The compiler only handles runes in those file types.
  5. 5. Why wrap a class method in an arrow function in onclick={() => counter.increment()}?

    Passing counter.increment alone detaches the method from its object, so this would be wrong.

Summary

  • let x = $state(initial) declares reactive state; plain assignment updates the page.
  • Updates are batched into one DOM flush.
  • Objects and arrays become deeply reactive proxies; push and property assignment work.
  • Copies and destructured values are not reactive.
  • Runes in modules require .svelte.js or .svelte.ts file names.

Next: Derived Values with $derived