0
0
SvelteHow-ToBeginner · 3 min read

How to Trigger Reactivity for Arrays in Svelte

In Svelte, to trigger reactivity for an array, you must assign a new value to the array variable using array = [...array] or similar. Direct mutations like array.push() do not trigger updates unless followed by reassignment.
📐

Syntax

In Svelte, reactivity depends on assignments. For arrays, you must reassign the array variable after changing it to trigger updates.

  • array = [...array]: Creates a new array copy and assigns it, triggering reactivity.
  • array = array.filter(...): Filters and reassigns the array.
  • array = array.map(...): Maps and reassigns the array.
svelte
let items = [1, 2, 3];

// To trigger reactivity after mutation:
items = [...items];
💻

Example

This example shows a list of numbers and a button to add a new number. The array is updated by pushing a new item, then reassigned to trigger reactivity and update the UI.

svelte
<script>
  let numbers = [1, 2, 3];

  function addNumber() {
    numbers.push(numbers.length + 1); // mutate array
    numbers = [...numbers]; // reassign to trigger reactivity
  }
</script>

<ul>
  {#each numbers as number}
    <li>{number}</li>
  {/each}
</ul>
<button on:click={addNumber}>Add Number</button>
Output
<ul><li>1</li><li>2</li><li>3</li></ul><button>Add Number</button>
⚠️

Common Pitfalls

Directly mutating an array like array.push() or array.splice() without reassigning the array will not update the UI because Svelte tracks assignments, not mutations.

Wrong approach:

numbers.push(4); // UI will not update

Right approach:

numbers.push(4);
numbers = [...numbers]; // triggers update
📊

Quick Reference

  • Always reassign the array variable after mutation to trigger reactivity.
  • Use spread syntax [...array] to create a new array copy.
  • Use array methods that return new arrays like filter or map with reassignment.
  • Remember Svelte tracks assignments, not internal mutations.

Key Takeaways

Svelte reactivity triggers only on assignments, not on direct array mutations.
Use array = [...array] after mutating an array to update the UI.
Array methods that return new arrays (like filter, map) should be reassigned to trigger reactivity.
Avoid mutating arrays without reassignment to prevent stale UI.
Reassigning the array creates a new reference, which Svelte detects for updates.