0 day streak
javascript / intermediate
Snippet

Ensuring Reactivity with Immutable Patterns

Svelte's reactivity is triggered by assignment (=). When working with arrays or objects, you must replace the entire reference rather than mutating properties directly to ensure Svelte detects the change and updates the UI.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
let tasks = [{ id: 1, text: 'Code', done: false }];
function toggleTask(id) {
// Trigger reactivity by creating a new reference via map
tasks = tasks.map(t =>
t.id === id ? { ...t, done: !t.done } : t
);
}
function addTask(text) {
// Spread operator ensures a new array reference
tasks = [...tasks, { id: Date.now(), text, done: false }];
}
svelte
Breakdown
1
tasks = tasks.map(t => ... )
The map method creates a new array, and the assignment (=) triggers Svelte's reactivity.
2
{ ...t, done: !t.done }
Uses the spread operator to create a shallow copy of the object with one modified property.
3
tasks = [...tasks, ...]
Creates a new array containing all old elements plus a new one, then assigns it back.