Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 35 ยท Reactivity with Runes

Deep Reactivity and Snapshots

How Svelte 5 proxies make objects and arrays deeply reactive, when to use $state.raw, $state.snapshot, SvelteMap and SvelteSet, and what breaks proxies.

In the $state lesson you saw that objects and arrays can be mutated and the page follows. This lesson explains how that works, where its limits are, and which tools exist for the edge cases: $state.raw, $state.snapshot, and the reactive versions of built-in collections.

Proxies, in plain words

When you write let user = $state({ name: 'Ada', tags: ['math'] }), Svelte does not store your object directly. It stores a proxy: a wrapper object that intercepts reads and writes. Reading user.name records "this reader depends on name". Writing user.name = 'Grace' notifies exactly those readers.

The proxy is deep: nested plain objects and arrays inside are wrapped on demand, so user.tags.push('logic') and user.address.city = 'Paris' are tracked too.

SVELTE
<script>
  let user = $state({ name: 'Ada', tags: ['math'], address: { city: 'London' } });
</script>

<input bind:value={user.name} />
<input bind:value={user.address.city} />
<button onclick={() => user.tags.push('logic')}>Add tag</button>
<p>{user.name} ({user.address.city}): {user.tags.join(', ')}</p>

What is proxied, and what is not

  • Plain objects ({}) and arrays are proxied.
  • Instances of classes are not proxied, unless the class itself uses $state fields.
  • Map, Set, Date, URL and similar built-ins are not made reactive by $state.

That last point matters: mutating a normal Map does not update the page. Svelte offers reactive replacements in svelte/reactivity: SvelteMap, SvelteSet, SvelteDate and SvelteURL.

SVELTE
<script>
  import { SvelteSet } from 'svelte/reactivity';

  const selected = new SvelteSet();
</script>

<button onclick={() => selected.add(selected.size + 1)}>Add</button>
<p>{selected.size} selected</p>

Identity: the proxy is not the original

Because of the wrapper, this surprises people:

SVELTE
<script>
  const original = { count: 0 };
  let wrapped = $state(original);

  wrapped.count = 5;
  console.log(original.count); // 0: the original was not changed
  console.log(wrapped === original); // false
</script>

Svelte clones the structure when it creates the proxy. Always use the $state variable, not the original object you passed in.

$state.raw: opt out of deep reactivity

Wrapping a very large object (a 50,000-row dataset, say) costs time and memory. If you never mutate its insides and instead replace the whole value, use $state.raw:

SVELTE
<script>
  let rows = $state.raw([]);

  async function load() {
    rows = await fetchRows(); // reassignment is tracked
  }

  function addRow(row) {
    rows = [...rows, row]; // new array each time
  }
</script>

With $state.raw, rows.push(x) would not update the page: only reassigning rows does. This also suits third-party objects that must not be wrapped in a proxy.

$state.snapshot: a plain copy

Proxies are not always welcome. Some APIs fail on them: structuredClone, some native functions, serializers, or code that compares objects. $state.snapshot returns a plain, non-reactive deep copy at that moment:

SVELTE
<script>
  let form = $state({ name: 'Ada', skills: ['math', 'code'] });

  function save() {
    const plain = $state.snapshot(form);
    const copy = structuredClone(plain);
    localStorage.setItem('draft', JSON.stringify(copy));
  }
</script>

You also need snapshots when you console.log state and want a readable value instead of an opaque proxy object. (Svelte's dev tools print them nicely, but a plain log of a proxy can look confusing.)

Passing state around

Remember that a primitive copied out of state is just a value. Objects keep their reactivity as long as you pass the proxy itself:

SVELTE
<script>
  import Editor from './Editor.svelte';
  let settings = $state({ theme: 'light', size: 14 });
</script>

<Editor {settings} />

If Editor mutates settings.theme = 'dark', the parent sees it, because both hold the same proxy. That works, but it makes data flow hard to follow in big apps; the Props and callbacks lessons show clearer patterns. Svelte warns when a child mutates a prop that was not declared bindable.

Stand-in: deep proxies and snapshots

This runnable stand-in builds a small deep proxy, logs which paths change, and then shows what a snapshot does: it strips the proxy so you get a plain value.

JS Deep proxy and snapshot (stand-in)

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

No output.

Each nested write reported its full path. Editing the snapshot left the original alone.

Mutation versus replacement (stand-in page)

Press "Mutate" a few times and nothing changes on screen; press "Replace" and the new length appears.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does mutating a plain Map inside $state not update the page?

    $state proxies plain objects and arrays. SvelteMap, SvelteSet and friends provide reactive built-ins.
  2. 2. When is $state.raw a good choice?

    $state.raw skips deep proxying, so only reassignment is tracked.
  3. 3. What does $state.snapshot return?

    Snapshots are useful for structuredClone, serialization and logging.
  4. 4. After let wrapped = $state(original); wrapped.count = 5, what is original.count?

    Svelte creates a proxy around a copy of the structure, so the original object is not mutated.

Summary

  • $state wraps plain objects and arrays in deep proxies; mutation is tracked.
  • Class instances and built-ins like Map are not proxied; use SvelteMap, SvelteSet, SvelteDate.
  • $state.raw skips proxying: reassign instead of mutating.
  • $state.snapshot gives a plain copy for APIs that dislike proxies.
  • The proxy is not the original object you passed in.

Next: Text, Expressions and Attributes