0
0
Svelteframework~3 mins

Why Array and object reactivity gotchas in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover the simple trick that makes your Svelte app update instantly when you change arrays or objects!

The Scenario

Imagine you have a list of tasks in your app. You add a new task by pushing it to an array or update a task property inside an object. But the screen does not update to show your changes.

The Problem

Directly changing arrays or objects in Svelte does not always trigger the screen to update. This happens because Svelte tracks changes by assignments, not by internal mutations. So, pushing to an array or changing an object property silently fails to refresh the UI.

The Solution

Svelte requires you to reassign the array or object after changing it. This tells Svelte the data changed and it should update the screen. For example, after pushing to an array, you write tasks = tasks to trigger reactivity.

Before vs After
Before
tasks.push(newTask); // UI does not update
After
tasks.push(newTask);
tasks = tasks; // UI updates
What It Enables

This understanding lets you build dynamic apps where changes to arrays and objects always show up instantly on screen.

Real Life Example

Think of a to-do list app where you add or check off tasks. Without proper reactivity, the list won't refresh when you update tasks, confusing users. Fixing this makes the app feel alive and responsive.

Key Takeaways

Direct mutations to arrays or objects don't trigger updates in Svelte.

You must reassign the variable after mutation to activate reactivity.

This small step ensures your UI always matches your data changes.