What $state hides

By Esteban Trillo7 min readWhy SvelteSvelte

Same rune, four different things: the compiler decides how much machinery each $state gets.
Same rune, four different things: the compiler decides how much machinery each $state gets.

Part 3 of a series on Svelte in 2026. Part 2 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:

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:

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 $stateOne 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.$state(…)plain valuenumber, never reassignedsignalnumber, reassignedproxyobject, only mutatedsignal holding a proxyobject, reassigned
On the server, all four compile to 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.”1

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.”2 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.”1 The proxy lets Svelte run code on every read and write, including through methods like push.

<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.”3 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).”1

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:

Declare the array with
  • [ … ] the arrayproxiedreassign only
  • { done, text } plain objectproxiedreassign only
  • new Map()not proxiedreassign only
  • new Date()not proxiedreassign only
  • new Plain() ordinary classnot proxiedreassign only
  • new Todo() with done = $state()reactive via its fieldreactive 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.4 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.”1 The constructor form is newer: it landed in 5.31, so older tutorials only show fields.5

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

Here’s the client output:

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.”1 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.”6 Sharing state across modules is part 8.

The two escape hatches

Two sub-runes cover the cases where the proxy is the wrong tool.7

$state.raw

Raw state “cannot be mutated; it can only be reassigned.”1 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.”6

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:

rows = rows.with(0, { ...rows[0], done: true });
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?

$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.”1 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.”8 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.1

Destructuring copies. let { done } = todos[0] reads the value once. The docs: the references “are evaluated at the point of destructuring.”1 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,”1 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.1

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.”9

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?

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.”6 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.1

Next: $derived, and values computed from state.

Footnotes

  1. Svelte docs, $state. ↩ ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9 ↩10 ↩11 ↩12

  2. React docs, State as a Snapshot. ↩

  3. React docs, Updating Objects in State. ↩

  4. Svelte docs, svelte/reactivity: “values in a reactive map are not made deeply reactive.” ↩

  5. Svelte changelog, 5.31.0: “allow state fields to be declared inside class constructors” (#15820). ↩

  6. Svelte docs, Best practices. ↩ ↩2 ↩3

  7. There’s also $state.eager, added in 5.41. It only matters with await expressions in components, which are still experimental (docs), so it belongs with the async parts of this series. ↩

  8. Svelte docs, Runtime warnings: state_proxy_equality_mismatch. ↩

  9. Svelte docs, Compiler warnings: state_referenced_locally. ↩

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.