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.
Practice
$: symbol do in a Svelte component?Solution
Step 1: Understand the role of
The$:in Svelte$:prefix is used to mark statements as reactive, meaning they automatically re-run when any variable they use changes.Step 2: Compare with other options
Options A, B, and D describe unrelated Svelte features: async imports, props, and scoped styles, which do not use$:.Final Answer:
It marks a statement as reactive, so it runs when its dependencies change. -> Option BQuick Check:
Reactive statement = runs on data change [OK]
- Confusing $: with props declaration
- Thinking $: imports modules
- Assuming $: styles CSS
Solution
Step 1: Identify correct reactive statement syntax
In Svelte, reactive statements start with$:followed by an assignment or expression, e.g.$: total = a + b;.Step 2: Eliminate incorrect options
let $: total = a + b; incorrectly places$:afterlet. reactive total = a + b; uses a non-existent keywordreactive. const $total = a + b; uses$in variable name incorrectly.Final Answer:
$: total = a + b; -> Option DQuick Check:
Reactive statement syntax = $: expression [OK]
- Using let or const with $: reactive statements
- Writing $: inside variable names
- Using non-existent keywords like reactive
let a = 2; let b = 3; $: sum = a + b; // Later in code b = 5;
What is the value of
sum after b changes?Solution
Step 1: Understand reactive statement behavior
The reactive statement$: sum = a + b;runs wheneveraorbchanges. Initially,a=2andb=3, sosum=5.Step 2: Update after changing
Whenbbchanges to 5, the reactive statement re-runs, updatingsum = 2 + 5 = 7. But note the options carefully: 8 is 8, which is 2 + 6, not correct. 7 is 7, which matches calculation.Final Answer:
7 -> Option AQuick Check:
sum updates automatically = 7 [OK]
- Not updating sum after b changes
- Adding wrong numbers
- Confusing initial and updated values
let count = 0; $: count = count + 1;
Solution
Step 1: Analyze reactive statement effect
The statement$: count = count + 1;runs whenevercountchanges. But it changescountitself, causing it to run again immediately, creating an infinite loop.Step 2: Check other options
Syntax error: missing semicolon after count declaration. is incorrect because semicolons are optional in JS. Reactive statements cannot use let variables. is false; reactive statements can use let variables. No error; this code increments count once. is wrong because the increment repeats endlessly.Final Answer:
This causes an infinite loop because count updates itself reactively. -> Option CQuick Check:
Reactive self-update causes infinite loop [OK]
- Ignoring infinite loops from self-updating reactive statements
- Thinking semicolons cause errors
- Believing reactive statements can't use let variables
discountedPrice only when price or discount change, but discount can sometimes be zero or null. Which reactive statement correctly handles this so discountedPrice is price when discount is falsy?Solution
Step 1: Understand the problem with falsy discount
Ifdiscountis zero or null, we wantdiscountedPriceto equalprice(no discount). A simple calculation without check will give wrong results.Step 2: Evaluate each option
$: discountedPrice = price - (price * discount); always subtractsprice * discount, so zero discount works but null may cause NaN. $: discountedPrice = discount ? price - (price * discount) : price; uses a conditional to check if discount is truthy, else returns price, correctly handling zero and null. $: discountedPrice = price - (price * (discount || 1)); usesdiscount || 1, which makes discount 1 if falsy, causing full price discount (wrong). $: discountedPrice = price * discount || price; multiplies price by discount or price, which gives wrong results when discount is zero.Final Answer:
$: discountedPrice = discount ? price - (price * discount) : price; -> Option AQuick Check:
Use conditional to handle falsy discount [OK]
- Ignoring falsy discount causing wrong calculations
- Using || 1 which changes discount incorrectly
- Assuming zero discount subtracts correctly without check
Ready to prove it?
Pass the test and this pattern moves unknown
