CHAPTER 05
Beginner
Reactivity in Svelte
Updated: May 18, 2026
5 min read
# CHAPTER 5
Reactivity in Svelte
1. Chapter Introduction
Svelte's reactivity is its most celebrated feature. In React, you callsetState(). In Vue, you use ref() or reactive(). In Svelte, you simply assign to a variable. That's it. The Svelte compiler detects that a variable is used in the template and generates targeted DOM update code automatically. This chapter fully explains how this magic works.
2. Learning Objectives
- Understand how Svelte's compiler creates reactive updates.
- Use reactive assignments to trigger DOM updates.
-
Use reactive declarations (
$:) for derived values.
- Use reactive blocks for side effects.
- Understand array and object reactivity caveats.
3. How Svelte Reactivity Works
text
4. Basic Reactive Assignment
svelte
5. Reactive Declarations $: — Derived Values
Reactive declarations are Svelte's computed properties. They automatically recalculate when their dependencies change:
svelte
6. Reactive Blocks — Side Effects
A$: block runs whenever any variable inside it changes:
svelte
7. Array and Object Reactivity — The Assignment Rule
Critical: Svelte only detects reactivity through assignment (=). Array mutations like .push() or .splice() do NOT trigger updates because they don't use =.
svelte
8. Mini Project: Live Counter App
svelte
9. Common Mistakes
-
Array mutations without reassignment:
arr.push(item)is the #1 beginner mistake. Always usearr = [...arr, item].
-
Circular reactive declarations:
$: a = b + 1; $: b = a + 1;creates an infinite loop. Reactive dependencies must be acyclic.
10. MCQs with Answers
Question 1
How does Svelte know when to update the DOM?
Question 2
Why does array.push(item) NOT trigger a Svelte reactivity update?
Question 3
What is the correct way to add an item to a reactive array?
Question 4
What does $: total = price * quantity create?
Question 5
In $: { console.log(name); }, when does this block run?
Question 6
Does object property assignment trigger reactivity?
Question 7
What happens to an $: reactive declaration when the component is created?
Question 8
Can you have multiple reactive declarations in one component?
Question 9
What would cause a circular reactive dependency?
Question 10
How is Svelte's reactivity simpler than React's useState?
11. Interview Questions
- Q: Explain how Svelte achieves reactivity without a Virtual DOM.
- Q: What is the "assignment rule" in Svelte and why does it exist?
12. Summary
Svelte's reactivity model is beautifully simple: assignment triggers updates. The compiler identifies where each variable is used in the template and generates surgical update functions. The$: prefix extends this to derived values and side effects. Understanding the assignment rule (especially for arrays) is the most critical piece of knowledge for writing correct Svelte code.