How to Use $: Reactive Statements in Svelte
In Svelte,
$: is used to create reactive statements that run automatically whenever their dependencies change. It lets you update variables or run code reactively without writing extra functions or event handlers.Syntax
The $: label marks a reactive statement in Svelte. It runs the code after it whenever any variable it uses changes.
Format:
$: statement;or for multiple lines:
$: {
// reactive code here
}Each time a variable inside the statement changes, Svelte re-runs the code automatically.
svelte
$: doubled = count * 2;Example
This example shows a counter and a reactive statement that doubles the count value automatically.
svelte
<script> let count = 0; $: doubled = count * 2; </script> <button on:click={() => count++}>Increment</button> <p>Count: {count}</p> <p>Doubled: {doubled}</p>
Output
A button labeled 'Increment'. Below it, text shows 'Count: 0' and 'Doubled: 0'. Clicking the button increases count and doubled updates automatically.
Common Pitfalls
- Forgetting that
$:runs whenever any dependency changes, so avoid heavy computations inside it. - Trying to assign to a reactive variable inside its own reactive statement causes infinite loops.
- Using
$:outside<script>tags or in places where reactive context is not available.
svelte
<script> let count = 0; // Wrong: causes infinite loop // $: count = count + 1; // Right: $: doubled = count * 2; </script>
Quick Reference
$: reactive statement cheat sheet
| Usage | Description |
|---|---|
| $: doubled = count * 2; | Runs when 'count' changes, updates 'doubled' automatically. |
| $: { console.log(count); } | Runs code block reactively when 'count' changes. |
| $: if (count > 5) alert('High count!'); | Runs conditional code reactively. |
| Avoid assigning to the same variable inside $: to prevent loops | Example: $: count = count + 1; causes infinite loop. |
Key Takeaways
Use
$: to run code reactively when dependencies change in Svelte.Reactive statements automatically update variables or run code without extra functions.
Avoid infinite loops by not assigning to the same variable inside its reactive statement.
Place
$: inside <script> tags only.Keep reactive code simple to maintain performance.