Performance: Reactive declarations (let)
Reactive declarations affect how efficiently the UI updates when data changes, impacting interaction responsiveness and rendering speed.
let count = 0; $: doubled = count * 2;
let count = 0; let doubled; function updateDoubled() { doubled = count * 2; } // called manually after count changes updateDoubled();
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual state update with functions | Multiple updates | Multiple reflows if not batched | Higher paint cost due to redundant changes | [X] Bad |
| Reactive declarations with $: | Single update per dependency change | Minimal reflows | Lower paint cost due to targeted updates | [OK] Good |
$: symbol do in a Svelte component?$: in Svelte$: prefix is used to declare reactive statements that automatically update when their dependencies change.$:.$: = C [OK]$: means reactive update in Svelte [OK]$: declares constants$: with import syntax$: comments codesum that adds a and b in Svelte?$: before the statement to update automatically when dependencies change.let sum = a + b; is a normal variable assignment without reactivity. sum := a + b; uses invalid syntax. const $sum = a + b; incorrectly uses const and a dollar sign in the variable name.$: sum = a + b; [OK]$: followed by assignment [OK]$: for reactive variablesconstsum after a changes to 5?let a = 2; let b = 3; $: sum = a + b; // Later in code a = 5;
$: sum = a + b; recalculates sum whenever a or b changes.a changesa = 2 and b = 3, so sum = 5. When a changes to 5, sum updates to 5 + 3 = 8.let x = 1; $: y = x * 2 $: z = y + 3
let can be used reactively. const is not required inside reactive declarations.const instead of letstatus that shows "High" if score is above 80, "Medium" if between 50 and 80, and "Low" otherwise. Which reactive declaration correctly implements this?$: status = score > 80 ? 'High' : score >= 50 ? 'Medium' : 'Low'; uses valid nested ternary syntax. let status = if (score > 80) 'High' else if (score >= 50) 'Medium' else 'Low'; uses invalid syntax (no if inside assignment). $: if score > 80 then status = 'High' else status = 'Low'; uses invalid syntax (no then keyword in JS). $: status = score > 80 && 'High' || score >= 50 && 'Medium' || 'Low'; uses logical operators that may cause incorrect evaluation.$: for reactive updatesPass the test and this pattern moves unknown