Performance: Reactive statements ($:)
Reactive statements affect how efficiently the UI updates when data changes, impacting interaction responsiveness and rendering speed.
let count = 0; $: doubled = count * 2; function increment() { count += 1; }
let count = 0; let doubled; function updateDoubled() { doubled = count * 2; } // Called manually after every count change function increment() { count += 1; updateDoubled(); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual update calls | Multiple updates triggered manually | Multiple reflows if UI updates after each call | Higher paint cost due to repeated changes | [X] Bad |
| Reactive statements ($:) | Single update triggered automatically | Single reflow per change | Lower paint cost due to batched updates | [OK] Good |
$: symbol do in a Svelte component?$: in Svelte$: prefix is used to mark statements as reactive, meaning they automatically re-run when any variable they use changes.$:.$: followed by an assignment or expression, e.g. $: total = a + b;.$: after let. reactive total = a + b; uses a non-existent keyword reactive. const $total = a + b; uses $ in variable name incorrectly.let a = 2; let b = 3; $: sum = a + b; // Later in code b = 5;
sum after b changes?$: sum = a + b; runs whenever a or b changes. Initially, a=2 and b=3, so sum=5.bb changes to 5, the reactive statement re-runs, updating sum = 2 + 5 = 7. But note the options carefully: 8 is 8, which is 2 + 6, not correct. 7 is 7, which matches calculation.let count = 0; $: count = count + 1;
$: count = count + 1; runs whenever count changes. But it changes count itself, causing it to run again immediately, creating an infinite loop.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?discount is zero or null, we want discountedPrice to equal price (no discount). A simple calculation without check will give wrong results.price * 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)); uses discount || 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.Pass the test and this pattern moves unknown