gotchajavascriptsvelteMajorpending
Svelte Reactivity Gotchas - Assignments vs Mutations
Viewed 0 times
sveltereactivityassignmentmutationrunes$statereactive
Problem
Svelte's reactivity only triggers on assignments, not mutations. Pushing to an array or modifying an object property doesn't update the UI.
Solution
Svelte's compiler tracks reactivity through assignments:
Svelte 5 runes ($state) fix most of these with deep reactivity.
<script>
let items = ['a', 'b', 'c'];
let user = { name: 'Alice', age: 30 };
// WON'T trigger reactivity
function addItemBad() {
items.push('d'); // Mutation - Svelte doesn't see it
}
// WILL trigger reactivity
function addItemGood() {
items = [...items, 'd']; // Assignment - Svelte reacts
// OR
items.push('d');
items = items; // Re-assignment triggers update
}
// Object properties - same rule
function updateNameBad() {
user.name = 'Bob'; // This DOES work (property assignment)
}
// But nested objects don't
let config = { settings: { theme: 'dark' } };
function updateTheme() {
config.settings.theme = 'light'; // Works in Svelte 5 runes
config = config; // Safe fallback for Svelte 4
}
// Reactive declarations
$: doubled = items.length * 2; // Auto-updates when items changes
$: if (items.length > 10) console.log('Many items!');
</script>Svelte 5 runes ($state) fix most of these with deep reactivity.
Why
Svelte uses compile-time reactivity based on assignment detection. The compiler rewrites assignments to include UI update calls, but it can't intercept method calls like .push().
Gotchas
- Array methods (push, splice, sort) don't trigger updates without re-assignment
- $: reactive declarations only run when their dependencies change - initial run is in order
Context
Building Svelte applications
Revisions (0)
No revisions yet.