# What $state hides

- Published: 2026-11-27
- Tags: Why Svelte, Svelte
- URL: https://devtrillo.com/writing/why-svelte-3-what-state-hides/

> Part 3 of a series on Svelte in 2026. [Part 2](/writing/why-svelte-2-svelte-is-a-compiler/) read the compiler's output for a counter. This part reads it for `$state`, and then follows the proxy until it stops.

Four variables in one component, all declared with the same rune:

```svelte title="Reassign.svelte"
<script>
  let todos = $state([{ done: false }]); // reassigned later
  let rows = $state.raw([{ id: 1 }]); // reassigned later
  let count = $state(0); // reassigned later
  let never = $state(0); // never reassigned
</script>
```

Svelte 5.57.2 compiles them into four different things:

```js title="Reassign.js (compiled)"
let todos = $.state($.proxy([{ done: false }]));
let rows = $.state([{ id: 1 }]);
let count = $.state(0);
let never = 0;
```

A number you never reassign stops being state at all. A number you do reassign becomes a signal. An array becomes a proxy, wrapped in a signal only if you reassign the variable; one you only mutate compiles to a bare `$.proxy([...])`. On the server, all four are plain values and the rune disappears.

**What the compiler makes of $state.** One box on the left, $state, fans out to four boxes on the right, one per compiled representation. A number that's never reassigned becomes a plain value. A number that's reassigned becomes a signal. An object or array that's only mutated becomes a proxy. An object or array that's also reassigned becomes a signal holding a proxy. On the server, all four are plain values.

So `$state` is one word for four representations, and the compiler picks one per variable from how you use it. Three of them are easy to live with. The proxy is where the surprises are, including a class that serializes to `{}` in the browser and to the full object on the server.

## A number you assign

The docs put the simple case well: "`count` is just a number, rather than an object or a function, and you can update it like you would update any other variable."[^state]

Reads see writes straight away. Run `count++` three times in a handler, then read `count`, and you get 3. In React you'd read the old value, because state is a snapshot: setting it "does not change the state variable you already have, but instead triggers a re-render."[^snapshot] The docs' own example calls `setNumber(number + 1)` three times in one click handler, and React re-renders "with `number` equal to `1` rather than `3`."

Svelte still batches the update. In my lab, three increments followed by one flush re-ran the effect reading `count` once, and that run saw 3. Writes are synchronous; the effects don't run once per write.

## Objects and arrays become proxies

Give `$state` an array or a plain object and you get "a deeply reactive _state proxy_."[^state] The proxy lets Svelte run code on every read and write, including through methods like `push`.

```svelte
<script>
  let todos = $state([
    { done: false, text: "add more todos" },
  ]);
</script>

<button onclick={() => (todos[0].done = !todos[0].done)}>toggle</button>
<button onclick={() => todos.push({ done: false, text: "eat lunch" })}>
  add
</button>
```

You mutate it like any object, and the updates are granular. I put three effects on that list, one reading `todos[0].done`, one reading `todos[0].text`, one reading `todos.length`. Toggling `done` re-ran only the first. The `push` re-ran only the third.

React asks the opposite of you: "treat any JavaScript object that you put into state as read-only," because "without using the state setting function, React has no idea that object has changed."[^readonly] You copy with spreads, or you install Immer so you can write mutations that produce copies. Svelte's proxy gives you Immer's syntax with no copies, and with the change tracked down to the property.

## Where the proxy stops

The docs give the rule: state is proxied recursively "until Svelte finds something other than an array or simple object (like a class or an object created with `Object.create`)."[^state]

That covers more than it sounds. A `Map` is a class. So are `Date` and `Set`, and so is anything you wrote with `class`. In the lab, `$state(new Map())` followed by `map.set(...)` updated nothing. A plain class instance didn't react either, whether I passed it to `$state` directly or pushed it into a `$state` array.

Pick a declaration and see what each value in the tree gets:

**How far does the proxy reach?** Declare the array with `$state` or `$state.raw`; the array holds everything below it:

| Value | `$state` | `$state.raw` |
| --- | --- | --- |
| `[ … ]` the array | proxied | reassign only |
| `{ done, text }` plain object | proxied | reassign only |
| `new Map()` | not proxied | reassign only |
| `new Date()` | not proxied | reassign only |
| `new Plain()` ordinary class | not proxied | reassign only |
| `new Todo()` with done = $state() | reactive via its field | reactive via its field |

For the built-ins, `svelte/reactivity` exports reactive `SvelteMap`, `SvelteSet`, `SvelteDate` and `SvelteURL`. The same `set` call on a `SvelteMap` re-ran the effect. Its values aren't made deeply reactive, though.[^reactivity] For your own classes, you put the state inside.

## Classes carry their own state

"Class instances are not proxied. Instead, you can use `$state` in class fields (whether public or private), or as the first assignment to a property immediately inside the `constructor`."[^state] The constructor form is newer: it landed in 5.31, so older tutorials only show fields.[^changelog]

```js title="todo.svelte.js"
export class Todo {
  done = $state(false);
  constructor(text) {
    this.text = $state(text);
  }
}
```

Here's the client output:

```js title="todo.js (compiled, client)"
export class Todo {
  #text;

  get text() {
    return $.get(this.#text);
  }

  set text(value) {
    $.set(this.#text, value, true);
  }

  #done = $.state(false);

  get done() {
    return $.get(this.#done);
  }

  set done(value) {
    $.set(this.#done, value, true);
  }

  constructor(text) {
    this.#text = $.state($.proxy(text));
  }
}
```

Each field became a private signal plus a getter and setter on the prototype. The docs point out the consequence: "the properties are not enumerable."[^state] Hold on to that; it comes back in the gotchas.

The best-practices page goes further than allowing classes. It says to "use classes with `$state` fields to share reactivity between components, instead of using stores."[^bp] Sharing state across modules is part 8.

## The two escape hatches

Two sub-runes cover the cases where the proxy is the wrong tool.[^eager]

### `$state.raw`

Raw state "cannot be mutated; it can only be _reassigned_."[^state] The docs recommend it for "large arrays and objects that you weren't planning to mutate anyway," and best practices names the usual case: "This is often the case with API responses."[^bp]

The cost it avoids is real. On my M1, building and reading a 100k-row array behind a deep proxy took hundreds of milliseconds against about 15 for `$state.raw`, an order of magnitude or more, from a noisy micro-benchmark.

Read "cannot be mutated" as "mutating it won't update anything." The docs' own example marks `person.age += 1` with "this will have no effect," and on screen that's right. In memory it isn't: in the lab, the write **did** change `age`. Nothing reacted, so the data and the screen disagree, and nothing tells you. To update raw state, reassign it:

```js
rows = rows.with(0, { ...rows[0], done: true });
```

**Quiz:** You load 5,000 rows with let rows = $state.raw(await res.json()). A checkbox handler runs rows[0].done = true. What does the user see?

- The first row's checkbox updates
- Nothing changes on screen, but rows[0].done is now true in memory
- It throws, because raw state is frozen

**Answer:** Nothing changes on screen, but rows[0].done is now true in memory — The write goes through to the plain object; Svelte just never hears about it. Reassign (rows = rows.with(0, {...})) or use $state if you mutate often.

- Not "The first row's checkbox updates": Raw state only reacts when you reassign the variable. A property write isn't tracked.
- Not "It throws, because raw state is frozen": That was $state.frozen, renamed to $state.raw before Svelte 5.0. Raw objects aren't frozen.

### `$state.snapshot`

A proxy is a real `Proxy`, and some APIs refuse one. `structuredClone` of a state proxy threw `DataCloneError: #<Object> could not be cloned.` in the lab. `$state.snapshot` exists for exactly that: passing state "to an external library or API that doesn't expect a proxy, such as `structuredClone`."[^state] It returns a plain copy.

`JSON.stringify` on a proxy works fine. It's classes that break JSON, as the next section shows.

## Gotchas

**Identity changes on the way in.** Push an object into a `$state` array and the array holds a proxy of it, not the object. The docs warn that equality checks against the original "will always return `false`."[^mismatch] In the lab, `todos.includes(lunch)` was `false` and `indexOf` was `-1` straight after `todos.push(lunch)`. A dev build logs `state_proxy_equality_mismatch`. A production build says nothing. Compare by id.

**Class state serializes differently on the client and the server.** I found this one in the lab, not in the docs. The docs only say the fields aren't enumerable. Here's what that does to `JSON.stringify(new Todo("x"))`:

```
server JSON: {"done":false,"text":"x"}
client JSON: {}
```

The server compiles the class to plain fields (`done = false; this.text = text`), so they serialize. The client compiles them to private fields behind prototype accessors, so `Object.keys`, spread and JSON all see nothing. `$state.snapshot` of the instance gives you an empty `{}` too. Defining `toJSON` on the class fixes both, because snapshot clones whatever `toJSON` returns.[^state]

**Destructuring copies.** `let { done } = todos[0]` reads the value once. The docs: the references "are evaluated at the point of destructuring."[^state] After a toggle, my destructured `done` was still `true` while `todos[0].done` was `false`.

**Functions get values, not variables.** "JavaScript is a _pass-by-value_ language,"[^state] so `track(count)` passes a number that never changes. Pass a getter (`() => count`) or the proxy itself. If you find yourself writing many getters, the docs suggest a class.

**`this` in handlers.** `onclick={todo.reset}` calls `reset` with `this` set to the `<button>`. Use `onclick={() => todo.reset()}`, or declare `reset` as an arrow-function field.[^state]

**Reading reassigned state at the top level.** `let start = count` in the script copies the value once. The compiler warns with `state_referenced_locally`, because the read "breaks the link."[^local]

**Quiz:** count starts at 0. A Svelte click handler runs count++; count++; console.log(count). What's logged, and how many times does the button text update?

- 2, and the text updates once
- 0, like React's state snapshot
- 2, and the text updates twice

**Answer:** 2, and the text updates once — Writes are synchronous, so the read sees 2. The DOM update is batched into one flush.

- Not "0, like React's state snapshot": That's React's model. A Svelte write changes the variable you're holding.
- Not "2, and the text updates twice": Updates are batched; the effect re-runs once per flush.

## One rune, a compiler deciding the rest

`$state` looks like a variable, and most of the time it acts like one. Underneath, the compiler picks between a constant, a signal, a proxy and a signal holding a proxy, and a class field becomes a private signal with accessors. The proxy is the part with edges: it stops at class instances, it changes object identity, it can't be cloned, and a class built on it serializes one way in the browser and another on the server.

The guidance from the docs is short. Use `$state` only for values that should be reactive, and "everything else can be a normal variable."[^bp] Use `$state.raw` for big data you replace rather than edit. Reach for `$state.snapshot` at the boundary with code that doesn't expect a proxy. The `$state` page itself is worth reading top to bottom; it's short, and most of this post's quotes come from it.[^state]

Next: `$derived`, and values computed from state.

[^state]: Svelte docs, [`$state`](https://svelte.dev/docs/svelte/$state).

[^snapshot]: React docs, [State as a Snapshot](https://react.dev/learn/state-as-a-snapshot).

[^readonly]: React docs, [Updating Objects in State](https://react.dev/learn/updating-objects-in-state).

[^reactivity]: Svelte docs, [`svelte/reactivity`](https://svelte.dev/docs/svelte/svelte-reactivity): "values in a reactive map are _not_ made deeply reactive."

[^changelog]: [Svelte changelog](https://github.com/sveltejs/svelte/blob/main/packages/svelte/CHANGELOG.md), 5.31.0: "allow state fields to be declared inside class constructors" (#15820).

[^bp]: Svelte docs, [Best practices](https://svelte.dev/docs/svelte/best-practices).

[^mismatch]: Svelte docs, [Runtime warnings: `state_proxy_equality_mismatch`](https://svelte.dev/docs/svelte/runtime-warnings#state_proxy_equality_mismatch).

[^local]: Svelte docs, [Compiler warnings: `state_referenced_locally`](https://svelte.dev/docs/svelte/compiler-warnings#state_referenced_locally).

[^eager]: There's also `$state.eager`, added in 5.41. It only matters with `await` expressions in components, which are still experimental ([docs](https://svelte.dev/docs/svelte/await-expressions)), so it belongs with the async parts of this series.

- **Part 4 — Svelte 4 had dependency arrays. You just never saw them.**: the dependency list moves to run time, and $derived does as little work as it can
