| | |

Svelte 9 ๐Ÿงก Deep Reactivity on Objects and Arrays with $state()

โฑ๏ธ Estimated read: 8 min | |

In modern Svelte applications, the management of complex data structures is handled through deep reactivity. When you declare an object or an array with the $state() rune, Svelte does not merely wrap the reference; it recursively traverses the structure and wraps every nested property in a reactive proxy. This ensures that any mutation, whether at the top level or buried several layers deep within an object graph, is immediately observed by the framework. The UI is then updated surgically, targeting only the affected DOM elements.

This recursive proxying is a significant departure from the legacy Svelte system, which relied on static analysis to detect assignments. By leveraging runtime proxies, Svelte 9 ensures that even the most complex state trees remain fully reactive without the developer needing to manually trigger re-renders or perform awkward “trigger assignments” like obj = obj. This chapter explores the mechanics of this deep reactivity, how it handles array manipulations, and the architecture required to maintain a performant and reactive application state.

Key point: The $state() rune recursively initializes a proxy tree where every nested property is tracked at the runtime level; consequently, any modification to a deeply nested value, whether it is a property assignment or an array method call, automatically propagates to any dependent UI components.


Why exists

The limitation of reference tracking. In traditional frameworks, tracking changes often requires diffing a virtual DOM tree. Deep reactivity exists to eliminate this overhead by knowing exactly which leaf node changed, allowing for direct updates.

The complexity of deep mutations. In standard JavaScript, mutating a nested property (e.g., a.b.c = 1) does not trigger any notification. Deep reactivity exists to bridge this gap, turning standard JS objects into observable reactive trees.

The ergonomics of mutability. Developers prefer using standard methods like .push() or .splice() on arrays. Deep reactivity allows these native methods to be used directly while maintaining the reactive integrity of the application.

The overhead of manual state management. Legacy systems often required developers to manually emit updates or replace objects with new copies to trigger updates. Deep reactivity removes this cognitive burden, letting developers write idiomatic code.

The challenge of partial updates. By tracking state at a granular level, Svelte 9 ensures that if one property in a large object changes, only the parts of the DOM relying on that property re-render, preserving the state of other elements.

The need for runtime consistency. Because proxies are native to the runtime, behavior remains consistent whether you are updating state inside a component, a Svelte file, or a plain TypeScript utility file.


a. The Proxy Mechanism: Recursive Initialization

When you call $state({ a: { b: 1 } }), Svelte does not just proxy the top-level object. It initializes a “deep proxy.” When you access state.a, Svelte returns a proxy for the inner object a. When you access state.a.b, you are reading from the inner-most proxy layer.

let state = $state({ user: { settings: { theme: "dark" } } });

// Accessing settings returns the settings proxy
let settings = state.user.settings; 
settings.theme = "light"; // This mutation is detected by the root proxy

This recursive structure allows the framework to build a dependency graph that spans the entire object tree. When a property is modified, the notification bubbles up to the root, identifying exactly which subscribersโ€”whether they are components or derived stateโ€”need to react.

b. Array Mutation and Collection Dynamics

Deep reactivity for arrays is built on the same proxy foundations. Svelte patches the standard array prototype methodsโ€”such as push, pop, shift, unshift, splice, and sortโ€”to intercept mutations. When an array method is called on a $state()-wrapped array, the proxy updates the internal reactive count and notifies observers.

let list = $state([1, 2, 3]);

// Standard array methods trigger updates
list.push(4); 
list.splice(1, 1);
list[0] = 99; // Index-based assignment is also reactive

Unlike legacy frameworks where you had to reassign the array (list = [...list, 4]), Svelte 9 treats the reactive array as a mutable source. This is not only cleaner but significantly faster because it avoids creating unnecessary shallow copies of large arrays.

c. Deeply Nested Object Updates

The power of deep reactivity becomes evident when dealing with complex data models, such as nested API responses or entity trees. Because the proxy intercepts both read and write operations, you can maintain a clean separation between your business logic and your UI templates.

let dashboard = $state({ 
  stats: { daily: { views: 0, clicks: 0 } } 
});

function trackView() {
  // Deep path mutation
  dashboard.stats.daily.views++;
}

The key to understanding this is that “reactivity” is tied to the proxy, not the object literal itself. If you assign a new object to a nested property, Svelte automatically “unwraps” the old object and “wraps” the new object in a new proxy, maintaining the reactive chain dynamically.


Complete Example Session

// ============================================
// PART 1: INITIALIZING DEEP STATE
// ============================================
let store = $state({
  meta: { version: 1.0 },
  users: [{ id: 1, active: true }, { id: 2, active: false }]
});

// ============================================
// PART 2: MODIFYING NESTED OBJECT
// ============================================
store.meta.version = 1.1;

// ============================================
// PART 3: ARRAY METHODS
// ============================================
store.users.push({ id: 3, active: true });

// ============================================
// PART 4: PROPERTY MUTATION IN ARRAY
// ============================================
store.users[0].active = false;

// ============================================
// PART 5: DYNAMIC PROPERTY ADDITION
// ============================================
// @ts-ignore
store.users[0].lastLogin = "2023-10-01"; // Dynamically added prop becomes reactive

// ============================================
// PART 6: REMOVING ELEMENTS
// ============================================
store.users.shift();

// ============================================
// PART 7: REPLACING A SUB-OBJECT
// ============================================
store.meta = { version: 2.0 }; // New object becomes a proxy

// ============================================
// PART 8: DERIVING FROM DEEP STATE
// ============================================
let userCount = $derived(store.users.length);

// ============================================
// PART 9: CONDITIONAL LOGIC
// ============================================
let status = $derived(store.users.some(u => u.active) ? "active" : "idle");

// ============================================
// PART 10: SNAPSHOTTING
// ============================================
let plain = $state.snapshot(store); // Raw object copy

These steps illustrate how deep reactivity handles the entire lifecycle of an object tree, from modification to derivation.


Quick Reference

Array Method Support

MethodBehavior
pushAppends and notifies
popRemoves and notifies
spliceModifies range and notifies
sortReorders and notifies
reverseReverses and notifies

Deep Reactivity Proxy Rules

OperationResult
obj.prop = valTriggers UI update
arr[i] = valTriggers UI update
delete obj.propTriggers UI update
Object.assignTriggers UI update

Snapshotting

CommandAction
$state.snapshot(o)Returns non-reactive copy
JSON.stringify(o)Works fine on proxy

Best Practices

โœ… Do This:

let data = $state({ list: [] });                              // โœ… Initialize properly
data.list.push(item);                                         // โœ… Use native methods
data.meta.timestamp = Date.now();                             // โœ… Mutate directly
let active = $derived(data.list.filter(i => i.active));       // โœ… Use derived
let { meta } = $state.snapshot(data);                         // โœ… Use snapshot

โŒ Don’t Do This:

let data = $state({ list: [] });
data = { list: [...data.list, item] };                        // โŒ Unnecessary reassign
data.list = data.list.concat(item);                           // โŒ Avoid copying
delete data.meta;                                             // โŒ (Use sparingly)
let list = data.list; list.push(item);                        // โŒ Destructuring breaks proxy

Common Pitfalls

PitfallWhy It HappensFix
DestructuringProxy is lost on primitiveAccess via parent object
...spreadSpread converts to plain objAccess deep properties directly
ReassignmentOverwriting existing proxyMutate internal properties
Array.map.map creates new arrayUse .push/.splice or reassign safely
Object.freezeBreaks proxy mutationAvoid freezing reactive objects

Real-World Examples

1. Todo List Management

let todos = $state([{ text: "Learn Svelte", done: false }]);
todos[0].done = true;

2. Settings Toggle

let settings = $state({ theme: { dark: true } });
settings.theme.dark = false;

3. Dynamic Form Array

let fields = $state([{ value: "" }]);
fields.push({ value: "New Field" });

4. Cart Logic

let cart = $state({ items: [] });
cart.items.push({ id: 1, qty: 1 });

5. User Profile Update

let user = $state({ profile: { bio: "" } });
user.profile.bio = "Hello World";

6. Analytics Counters

let stats = $state({ clicks: 0, views: 0 });
stats.clicks++;

7. Grid Data

let grid = $state([[1, 2], [3, 4]]);
grid[0][1] = 99;

8. Tab Selection

let ui = $state({ activeTab: 0 });
ui.activeTab = 1;

9. Filtering Reactive Arrays

let filtered = $derived(items.filter(i => i.show));

10. API Data Wrapper

let cache = $state({ users: {} });
cache.users[id] = data;

Visual

Proxy Tree Structure

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  ROOT PROXY (store)                          โ”‚
โ”‚  โ”œโ”€โ”€ meta (Proxy)                            โ”‚
โ”‚  โ”‚   โ””โ”€โ”€ version (Number)  <โ”€โ”€ Leaf Node     โ”‚
โ”‚  โ””โ”€โ”€ users (Proxy Array)                     โ”‚
โ”‚      โ””โ”€โ”€ [0] (Proxy Object)                  โ”‚
โ”‚          โ””โ”€โ”€ active (Boolean) <โ”€โ”€ Leaf Node  โ”‚
โ”‚                                              โ”‚
โ”‚  Updates flow from leaves to root.           โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Mutation vs Reassignment

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  MUTATION (Deep Reactive)                    โ”‚
โ”‚  store.users[0].active = true;               โ”‚
โ”‚  โ”Œโ”€โ”€ Proxy detected change                   โ”‚
โ”‚  โ””โ”€โ”€ UI updates only for user[0]             โ”‚
โ”‚                                              โ”‚
โ”‚  REASSIGNMENT (Inefficient)                  โ”‚
โ”‚  store.users = [...newUsers];                โ”‚
โ”‚  โ”Œโ”€โ”€ Proxy creates new object                โ”‚
โ”‚  โ””โ”€โ”€ Entire list re-rendered                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Proxy Unwrapping

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  const obj = { val: 10 };                    โ”‚
โ”‚  let state = $state(obj);                    โ”‚
โ”‚                                              โ”‚
โ”‚  state.val = 20;  // Mutation works          โ”‚
โ”‚  obj.val = 20;    // Mutation works (Proxy)  โ”‚
โ”‚                                              โ”‚
โ”‚  Proxy maintains reference mapping.          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
Deep mechanismRecursive Proxy
Array mutationNative method patching
Nesting limitNone (constrained by RAM)
PerformanceO(1) update complexity
Best practiceMutate in place

Key takeaways:

  • Deep reactivity is recursive. Svelte 9 automatically proxies all nested objects and arrays within a $state() container, ensuring every mutation is tracked.
  • Native methods work out of the box. You can use standard JavaScript mutation patterns like .push() on arrays or property assignment on objects without workarounds.
  • Proxies track indices and keys. Accessing array[0] or object.key is tracked, enabling surgical DOM updates that do not require full parent re-renders.
  • Snapshot for non-reactive needs. Use $state.snapshot() when you need a plain, non-reactive copy of your data for external libraries or logging.
  • Avoid unnecessary reassignments. Reassigning a reactive object replaces the proxy and can break existing references, whereas mutating the object keeps the reactive chain alive.

Remember: Deep reactivity is the backbone of Svelte 9’s performance and developer experience. By transforming your data into observable proxy trees at runtime, Svelte allows you to focus on building features using idiomatic JavaScript while the framework handles the complex synchronization between your state and the browser DOM. Always prioritize in-place mutations over object replacement to keep your reactive graph healthy and efficient.

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!