0
0
SvelteHow-ToBeginner · 3 min read

How to Trigger Reactivity for Object in Svelte

In Svelte, to trigger reactivity for an object, you must assign the object itself after changing its properties, like obj = {...obj, key: value} or obj = obj. Directly mutating object properties without reassignment does not update the UI because Svelte tracks assignments, not deep mutations.
📐

Syntax

In Svelte, reactivity depends on assignments. To update an object reactively, you must assign it a new value or reassign it after mutation.

  • obj = {...obj, key: newValue}: Creates a new object with updated properties.
  • obj = obj: Reassigns the same object to trigger reactivity after mutation.
svelte
let obj = { count: 0 };

// Reactive update by creating a new object
obj = { ...obj, count: obj.count + 1 };

// Or reactive update by reassigning after mutation
obj.count += 1;
obj = obj;
💻

Example

This example shows a counter object whose count property updates reactively when a button is clicked. It uses object reassignment to trigger Svelte's reactivity.

svelte
<script>
  let counter = { count: 0 };

  function increment() {
    // Mutate property
    counter.count += 1;
    // Reassign object to trigger reactivity
    counter = counter;
  }
</script>

<button on:click={increment} aria-label="Increment counter">Increment</button>
<p>Count: {counter.count}</p>
Output
Count: 0 (initially) After clicking 'Increment' button, count increases by 1 each time.
⚠️

Common Pitfalls

A common mistake is mutating object properties without reassigning the object, which does not trigger UI updates in Svelte.

Wrong approach:

let obj = { value: 1 };
obj.value = 2; // UI will NOT update because no assignment to obj

Right approach:

obj = { ...obj, value: 2 }; // Creates new object and triggers reactivity

Or reassign after mutation:

obj.value = 2;
obj = obj; // Reassignment triggers reactivity
📊

Quick Reference

Tips to trigger reactivity for objects in Svelte:

  • Always assign the object after changing properties.
  • Use spread syntax { ...obj, key: value } to create a new object.
  • Or reassign the same object obj = obj after mutation.
  • Direct property mutation without assignment does not update the UI.

Key Takeaways

Svelte tracks reactivity by assignments, not by deep object mutations.
To update an object reactively, assign a new object or reassign the existing one.
Use spread syntax to create a new object with updated properties.
Reassigning the same object after mutation also triggers reactivity.
Directly changing object properties without assignment will not update the UI.