What if your code could update itself automatically whenever data changes, without you lifting a finger?
Why Reactive statements ($:) in Svelte? - Purpose & Use Cases
Imagine you have a webpage where you want to show the total price that updates every time the user changes the quantity or price of items.
You try to update the total manually by writing code that listens to every input change and recalculates the total yourself.
Manually tracking every change and updating the total is tiring and easy to forget.
If you miss updating the total somewhere, the page shows wrong information.
This leads to bugs and a frustrating experience for both you and the users.
Reactive statements in Svelte automatically run code whenever the values they depend on change.
You just write the calculation once, and Svelte keeps it updated for you.
function updateTotal() {
total = price * quantity;
}
inputPrice.onchange = updateTotal;
inputQuantity.onchange = updateTotal;$: total = price * quantity;
This lets you write simple, clear code that always keeps your data and UI in sync without extra work.
Think of a shopping cart where the total price updates instantly as you change item amounts, without you writing extra event handlers.
Reactive statements run automatically when their data changes.
They reduce bugs by keeping calculations in one place.
They make your code simpler and easier to read.