0
0
Svelteframework~5 mins

Immutable patterns for updates in Svelte

Choose your learning style9 modes available
Introduction

Immutable patterns help keep your data safe by not changing the original values. This makes your app easier to understand and bugs easier to find.

When you want to update a list or object without changing the original data.
When you want to trigger Svelte reactivity by creating new values.
When you want to keep a history of changes for undo or debugging.
When you want to avoid unexpected side effects from shared data.
When working with stores or props that should not be mutated directly.
Syntax
Svelte
// Updating an array immutably
let newArray = [...oldArray, newItem];

// Updating an object immutably
let newObject = {...oldObject, key: newValue};

Use the spread operator ... to copy arrays or objects.

Always assign the new value to trigger Svelte's reactivity.

Examples
Adds 4 to the end of the numbers array without changing the original array.
Svelte
let numbers = [1, 2, 3];
numbers = [...numbers, 4];
Creates a new user object with an updated age, keeping other properties the same.
Svelte
let user = { name: 'Anna', age: 25 };
user = { ...user, age: 26 };
Updates the done status of a todo item immutably by creating a new array and new object for the changed item.
Svelte
let todos = [{ id: 1, done: false }];
todos = todos.map(todo => todo.id === 1 ? { ...todo, done: true } : todo);
Sample Program

This Svelte component shows a list of fruits. When you click buttons, it updates the list immutably by creating new arrays. This triggers Svelte to update the displayed list.

Svelte
<script>
  let items = ['apple', 'banana'];

  function addItem(newItem) {
    // Use immutable update to add new item
    items = [...items, newItem];
  }

  function updateFirstItem(newName) {
    // Update first item immutably
    items = items.map((item, index) => index === 0 ? newName : item);
  }
</script>

<h2>Fruits:</h2>
<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>

<button on:click={() => addItem('orange')}>Add Orange</button>
<button on:click={() => updateFirstItem('grape')}>Change First to Grape</button>
OutputSuccess
Important Notes

Directly changing arrays or objects (like items.push()) won't trigger Svelte updates.

Immutable updates help Svelte detect changes and update the UI efficiently.

Use immutable patterns especially when working with stores or passing props.

Summary

Immutable updates create new arrays or objects instead of changing originals.

This helps Svelte know when to update the screen.

Use the spread operator and array methods like map for easy immutable updates.