Reactive statements let your code automatically update when data changes. This helps keep your app in sync without extra work.
0
0
Reactive statements ($:) in Svelte
Introduction
You want to update a value whenever another value changes.
You need to run some code automatically after a variable updates.
You want to keep your UI and data connected easily.
You want to avoid writing manual event handlers for simple updates.
Syntax
Svelte
$: statement_or_assignment;
The $: prefix marks a reactive statement.
It runs whenever any variable it uses changes.
Examples
This sets
doubled to twice count whenever count changes.Svelte
$: doubled = count * 2;This logs a message every time
count updates.Svelte
$: console.log('Count changed:', count);
You can use a block to run multiple statements reactively.
Svelte
$: {
total = price * quantity;
console.log('Total updated:', total);
}Sample Program
This Svelte component shows a button that increases count. The doubled value updates automatically using a reactive statement. The UI updates to show both values.
Svelte
<script> let count = 0; $: doubled = count * 2; </script> <button on:click={() => count++} aria-label="Increase count">Increase</button> <p>Count: {count}</p> <p>Doubled: {doubled}</p>
OutputSuccess
Important Notes
Reactive statements run after the component updates the variables they depend on.
You can use reactive statements for calculations, side effects, or logging.
Be careful to avoid infinite loops by not updating a variable inside its own reactive statement without conditions.
Summary
Reactive statements automatically run when their data changes.
Use $: before a statement or assignment to make it reactive.
This helps keep your UI and data in sync easily.