How Reactivity Works in Svelte: Simple Explanation and Examples
In Svelte,
reactivity works by automatically updating the UI when variables change using a special syntax with the $: label for reactive statements. Assigning to variables triggers updates without needing extra code, making it simple and efficient.Syntax
Svelte uses a special label $: to mark reactive statements that run whenever referenced variables change. Assigning a new value to a variable automatically updates the UI. You can also create reactive variables that depend on others.
let count = 0;declares a reactive variable.$: doubled = count * 2;recalculatesdoubledwhenevercountchanges.$: console.log(count);runs the statement reactively oncountchange.
svelte
let count = 0; $: doubled = count * 2; $: console.log('Count changed:', count);
Example
This example shows a button that increments a counter. The doubled value updates automatically and the UI reflects changes instantly without manual DOM updates.
svelte
<script> let count = 0; $: doubled = count * 2; </script> <button on:click={() => count++} aria-label="Increment count">Increment</button> <p>Count: {count}</p> <p>Doubled: {doubled}</p>
Output
Button labeled 'Increment'
Count: 0
Doubled: 0
(Clicking the button increases count and doubled updates accordingly)
Common Pitfalls
One common mistake is trying to mutate objects or arrays without reassigning them, which Svelte won't detect as a change. Always reassign the variable to trigger reactivity.
Also, reactive statements run whenever referenced variables change, so avoid heavy computations inside them without conditions.
svelte
/* Wrong: mutating array without reassignment */ let items = [1, 2, 3]; items.push(4); // UI won't update /* Right: reassign to trigger update */ items = [...items, 4];
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Reactive declaration | Runs code when dependencies change | $: doubled = count * 2; |
| Reactive statement | Runs any statement reactively | $: console.log(count); |
| Variable assignment | Triggers UI update | count = count + 1; |
| Array/object mutation | Must reassign to update UI | items = [...items, newItem]; |
Key Takeaways
Use
$: to create reactive statements that update automatically.Assigning to variables triggers UI updates without extra code.
Always reassign arrays or objects after mutation to trigger reactivity.
Avoid heavy computations directly inside reactive statements.
Svelte's reactivity makes UI updates simple and efficient.