Reactive declarations let your code automatically update when data changes. It helps keep your app in sync without extra work.
Reactive declarations (let) in Svelte
let derived = expression;
$: derived = expression;The $: label marks a reactive declaration.
Whenever variables inside the expression change, the reactive declaration runs again.
doubled that updates when count changes.let count = 0; $: doubled = count * 2;
greeting updates automatically when name changes.let name = 'Alice'; $: greeting = `Hello, ${name}!`;
sum recalculates whenever a or b changes.let a = 5; let b = 10; $: sum = a + b;
This Svelte component shows a button with a count. When you click it, count increases. The doubled value updates automatically and shows below.
It uses a reactive declaration $: doubled = count * 2; to keep doubled in sync.
<script> let count = 1; $: doubled = count * 2; function increment() { count += 1; } </script> <button on:click={increment} aria-label="Increase count">Count: {count}</button> <p>Doubled value: {doubled}</p>
Reactive declarations run after the component initializes and whenever dependencies change.
You can use multiple reactive declarations in one component.
Use let to declare variables that will change; reactive declarations update them automatically.
Reactive declarations automatically update values when dependencies change.
Use $: before a statement to make it reactive.
This helps keep your UI and data in sync with less code.