In Svelte, changes to arrays or objects might not update the screen automatically. This happens because Svelte needs to know when data changes to refresh the view.
Array and object reactivity gotchas in Svelte
let items = [1, 2, 3]; // Wrong way: items[0] = 10; // UI might not update // Correct way: items[0] = 10; items = [...items]; // reassign to trigger update let user = { name: 'Alice', age: 25 }; // Wrong way: user.name = 'Bob'; // UI might not update // Correct way: user = { ...user, name: 'Bob' }; // reassign to trigger update
Svelte tracks changes by assignments. Directly changing array elements or object properties does not count as an assignment.
To update arrays or objects reactively, you must reassign the whole array or object.
let numbers = [1, 2, 3]; numbers[0] = 10; // UI might not update // Fix: numbers = [...numbers];
let colors = []; colors.push('red'); // UI might not update // Fix: colors = [...colors];
let profile = { name: 'Sam', age: 30 }; profile.age = 31; // UI might not update // Fix: profile = { ...profile, age: 31 };
let emptyObj = {}; emptyObj.newProp = 'value'; // UI might not update // Fix: emptyObj = { ...emptyObj, newProp: 'value' };
This Svelte component shows a list of fruits and user info. Buttons update the array and object. Without reassigning, the UI won't refresh. Using spread syntax to create new copies triggers Svelte's reactivity.
<script> let fruits = ['apple', 'banana', 'cherry']; let user = { name: 'Anna', city: 'Paris' }; function updateFirstFruit() { fruits[0] = 'apricot'; // This alone won't update the UI fruits = [...fruits]; // Reassign to trigger update } function addFruit() { fruits.push('date'); // This alone won't update the UI fruits = [...fruits]; // Reassign to trigger update } function changeUserCity() { user.city = 'London'; // This alone won't update the UI user = { ...user }; // Reassign to trigger update } </script> <h2>Fruits:</h2> <ul> {#each fruits as fruit} <li>{fruit}</li> {/each} </ul> <button on:click={updateFirstFruit}>Change first fruit</button> <button on:click={addFruit}>Add fruit</button> <h2>User Info:</h2> <p>Name: {user.name}</p> <p>City: {user.city}</p> <button on:click={changeUserCity}>Change city</button>
Time complexity: Reassigning arrays or objects copies data, so large data can be slower.
Space complexity: Creating new copies uses extra memory temporarily.
Common mistake: Changing array elements or object properties directly without reassigning.
Use this approach whenever you want Svelte to notice changes inside arrays or objects.
Svelte updates the UI only when you assign new values to variables.
Direct changes inside arrays or objects do not trigger updates.
Always reassign arrays or objects using spread syntax to make changes reactive.