0 day streak
javascript / intermediate
Snippet

Reactive Declarations for Derived State

Reactive declarations in Svelte use the '$:' label to automatically re-run code whenever its dependencies change. This is the idiomatic way to handle derived state or reactive side-effects within a component without manual event listeners.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script>
let count = 1;
$: doubled = count * 2;
$: if (doubled > 10) {
console.log('Threshold exceeded!');
}
</script>
<button on:click={() => count++}>
Increment: {count}
</button>
<p>Doubled: {doubled}</p>
svelte
Breakdown
1
$: doubled = count * 2;
Declares a reactive variable that updates whenever 'count' changes.
2
$: if (doubled > 10) { ... }
A reactive block that executes as a side-effect when 'doubled' satisfies the condition.