| | |

Svelte State 04 🧡 Fine-Grained Reactivity Control — Choosing between deep $state(), shallow $state.raw(), $state.snapshot(), and untrack()

⏱️ Estimated read: 7 min | |

Most Svelte 5 applications thrive using the standard $state() rune, which automatically creates deep reactive proxies. However, as applications grow in scale—handling large datasets, integrating third-party non-reactive libraries, or requiring high-performance calculations—the default “deep reactivity” can become a bottleneck. Svelte provides a suite of surgical tools to fine-tune exactly when and how reactivity is applied.

This chapter explores these precision tools: $state.raw() for bypassing proxy overhead, $state.snapshot() for exiting the reactive system safely, and untrack() for isolating side effects from dependency tracking. By moving beyond default reactivity, you gain the ability to build high-performance interfaces that remain predictable, manageable, and performant even when handling complex or massive data structures.

Key point: $state() is for standard reactive UI data, $state.raw() is for high-performance data that doesn’t need to trigger UI updates, $state.snapshot() captures a frozen, non-reactive copy of state, and untrack() prevents dependencies from being registered during state access.


Why exists

  • The Proxy Overhead problem. Deeply nested objects wrapped in recursive proxies can be expensive for very large arrays or data objects, potentially slowing down access times.
  • The Library Interop problem. Libraries like Three.js or D3.js often manipulate objects in ways that clash with Svelte’s reactive proxies; $state.raw() provides an “escape hatch.”
  • The Snapshot Requirement. Passing reactive state to third-party tools that expect plain JavaScript objects (like localStorage or fetch) requires a “snapshotted” version of the state to avoid side effects or circular references.
  • The Unintended Trigger problem. Sometimes, you need to read a value inside an effect without causing the effect to re-run when that value changes; untrack() provides this surgical control.
  • The Performance Optimization goal. By intentionally choosing shallow or raw state, you reduce memory consumption and CPU cycles spent on tracking changes that don’t matter to the UI.

a. Deep $state() vs $state.raw()

$state() wraps your data in a reactive proxy. Every time you access a property, Svelte tracks that access. Every time you modify it, Svelte triggers an update. For 95% of UI state, this is exactly what you want. However, $state.raw() stores the value without making it reactive. Reassigning it still triggers an update, but modifying its internal properties does not.

// Standard deep reactivity
let user = $state({ profile: { name: 'Dev' } });
user.profile.name = 'New'; // UI updates

// Shallow/Raw reactivity
let data = $state.raw({ items: [] });
data.items.push(1); // UI does NOT update
data = { items: [1] }; // UI updates (reassignment)

Use $state.raw() for massive datasets (thousands of items) where you only perform bulk updates or for objects managed by external libraries that don’t play well with proxy-based observation.

b. $state.snapshot()

Reactivity is contagious. If you pass a $state object to a function, that function receives a reactive proxy, not the underlying data. $state.snapshot() takes a reactive object and returns a “deeply cloned” plain JavaScript object. It is a static, frozen view of the data.

let state = $state({ count: 1 });
let plain = $state.snapshot(state);

// plain is now a regular object { count: 1 }
// Changing state.count will NOT change plain.count

Snapshots are essential when you need to send data to an API, save it to localStorage, or pass it to an external helper function that would otherwise break if it encountered a Svelte Proxy.

c. The power of untrack()

untrack() is used to prevent the current reactive context (like an $effect or $derived) from creating a dependency on a piece of state. It allows you to “peek” at a value without subscribing to its future changes.

$effect(() => {
  const current = untrack(() => counter.value);
  console.log(`Current value is ${current}, but I won't re-run when counter changes.`);
});

This is vital for “when this happens, check that” logic. Use it when you want to read a global configuration or a side-status without making your core effect re-trigger every single time that status fluctuates.


Complete Example Session

// ============================================
// PART 1: DEEP STATE (STANDARD)
// ============================================
let user = $state({ name: 'Alice' });

// ============================================
// PART 2: RAW STATE (PERFORMANCE)
// ============================================
let bigList = $state.raw(Array(10000).fill(0));

// ============================================
// PART 3: SNAPSHOT (EXIT REACTIVITY)
// ============================================
function save() {
  const data = $state.snapshot(user);
  localStorage.setItem('user', JSON.stringify(data));
}

// ============================================
// PART 4: UNTRACK (PEEKING)
// ============================================
$effect(() => {
  const val = untrack(() => user.name);
  // effect runs once, doesn't re-run on user.name change
});

This session demonstrates how standard reactivity, high-performance data, serialization, and dependency isolation work together in one flow.


Quick Reference

Reactivity Primitives

PrimitiveReactivityUse Case
$stateDeep/ProxyStandard UI state
$state.rawShallowMassive data/Third-party libs
$state.snapshotNone (Cloned)Serialization/Exporting
untrackIsolatedPeeking without subscribing

Lifecycle Behaviors

ActionResult
Mutate $stateUI update
Mutate $state.rawNo UI update (reassign required)
$state.snapshotFrozen, plain object

Best Practices

✅ Do This:

// Snapshot for serialization
localStorage.setItem('data', JSON.stringify($state.snapshot(data))); // ✅

// Use raw for external libraries
let map = $state.raw(new Map()); // ✅

// Use untrack for side-effects that don't depend on input
$effect(() => { const v = untrack(() => val); log(v); }); // ✅

❌ Don’t Do This:

// Don't use raw state if you need the UI to update
data.push(1); // (No UI update for raw)                // ❌

// Don't modify snapshots
const s = $state.snapshot(data); s.name = 'x'; // (No effect)   // ❌

// Don't over-use untrack
// (can lead to stale data bugs)                                // ❌

Common Pitfalls

PitfallWhy It HappensFix
No UI updateUsing $state.rawReassign the variable
Proxy errorPassing Proxy to 3rd partyUse $state.snapshot
Effect loopReading state in effectUse untrack for the value

Real-World Examples

1. Snapshotting form for submit

const payload = $state.snapshot(formData);

2. Raw list for high-freq updates

let items = $state.raw(largeArray);

3. Untracked logging

$effect(() => { console.log(untrack(() => count)); });

4. Avoiding circular proxies

const plain = $state.snapshot(complex);

5. Three.js scene object

let scene = $state.raw(new THREE.Scene());

6. Bulk update trigger

bigList = [...bigList, newItem];

7. Read-only side effect

untrack(() => settings.theme);

8. LocalStorage export

save(JSON.stringify($state.snapshot(state)));

9. Map/Set storage

let map = $state.raw(new Map());

10. Performance optimization

if (largeArray.length > 5000) return $state.raw(largeArray);

Visual

The Reactive Proxy Boundary

┌──────────────────────────────────────────────┐
│  DATA (Standard) ──► Proxy ──► UI Update     │
│  DATA (Raw)      ──► No Proxy ──► No Update  │
└──────────────────────────────────────────────┘

Snapshot vs Proxy

┌──────────────────────────────────────────────┐
│  REACTIVE OBJECT ──► $state.snapshot()       │
│                           │                  │
│  [ PLAIN JS OBJECT ] ◄────┘                  │
│  (Deep copy, no reactivity, static)          │
└──────────────────────────────────────────────┘

Untracking Dependencies

┌──────────────────────────────────────────────┐
│  Effect Scope                              │
│  ┌──────────────────────────────────────┐    │
│  │ State A ──► Dependency registered    │    │
│  │                                      │    │
│  │ untrack(State B) ──► Peeked          │    │
│  └──────────────────────────────────────┘    │
└──────────────────────────────────────────────┘

Summary

ItemValue
Deep Reactivity$state
Non-Reactive Container$state.raw
Frozen Copy$state.snapshot
Dependency Isolationuntrack

Key takeaways:

  • Standardize on $state. Always start with $state() unless you have a proven performance or interop issue.
  • Use $state.raw() for performance. It is the primary tool for avoiding the “proxy tax” on massive collections or non-reactive data structures.
  • Snapshots are for output. Whenever you need to move data out of Svelte (API calls, storage, 3rd party tools), snapshot it first to ensure you have a plain, clean object.
  • untrack() is for peeking. Use it to read values inside effects without adding them to the effect’s dependency graph.
  • Performance is an engineering choice. Fine-grained control is powerful, but use it sparingly; premature optimization with raw state can make code harder to read and debug.

Remember: Svelte’s default reactivity is smart enough for almost everything, but these four tools grant you the “surgeon’s scalpel” when things get complex. Whether you’re optimizing a list of 10,000 items, integrating a complex library, or preventing an effect from running too often, these primitives allow you to enforce your application’s architecture exactly where and when you need it.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!