0
0
SvelteDebug / FixBeginner · 3 min read

How to Fix Reactivity Not Working in Svelte

In Svelte, reactivity does not work if you directly mutate variables without reassigning them. Use variable = variable or the $: reactive statement to notify Svelte of changes and trigger updates.
🔍

Why This Happens

Svelte tracks changes by detecting when variables are reassigned. If you change a property of an object or an array element without reassigning the variable itself, Svelte won't notice the change and won't update the UI.

svelte
let count = 0;

function increment() {
  count++;
  // Reassignment happens here because count++ is equivalent to count = count + 1
}

<button on:click={increment}>Clicked {count} times</button>
Output
<button>Clicked 0 times</button> (button click updates count display)
🔧

The Fix

To fix this, always reassign the variable after changing it. For example, use count = count + 1 or count += 1. For objects or arrays, create a new copy or reassign the variable after mutation. This tells Svelte to update the UI.

svelte
let count = 0;

function increment() {
  count = count + 1; // Reassignment triggers reactivity
}

<button on:click={increment}>Clicked {count} times</button>
Output
<button>Clicked 0 times</button> (updates to 'Clicked 1 times', 'Clicked 2 times', etc. on clicks)
🛡️

Prevention

Always reassign variables when updating state in Svelte. Use the $: reactive label for derived values. Avoid mutating objects or arrays directly; instead, create new copies or reassign after mutation. Use linting tools like svelte-check to catch common mistakes early.

⚠️

Related Errors

Other common reactivity issues include forgetting to declare variables with let or const, or trying to update props passed from a parent component directly. Always update local state or dispatch events to notify parents.

Key Takeaways

Svelte reactivity requires variable reassignment to detect changes.
Mutating objects or arrays directly without reassignment breaks reactivity.
Use the $: label for reactive statements and derived values.
Lint your code with svelte-check to catch reactivity mistakes early.
Never update props directly; use events or local state instead.