Performance: Reactive blocks for side effects
This affects how efficiently the browser updates the UI and runs side effects when reactive data changes.
let count = 0; $: if (count !== 0) { console.log('Count changed:', count); // side effect runs only when count changes and meets condition }
let count = 0; $: { console.log('Count changed:', count); // heavy side effect here }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Unconditional reactive block with heavy side effects | Multiple DOM updates if side effects modify DOM | Multiple reflows if layout changes | High paint cost due to frequent updates | [X] Bad |
| Conditional reactive block limiting side effects | Minimal DOM updates only when needed | Single or no reflows if no layout changes | Low paint cost due to fewer updates | [OK] Good |
$: do in Svelte?$: in Svelte$: label creates a reactive block that runs code automatically when variables it uses change.$: label followed by a block or statement to create reactive code.$: { ... } which is the correct way to write a reactive block.let count = 0;
$: console.log(`Count is ${count}`);
function increment() {
count += 1;
}increment() function is called?count whenever count changes.increment()increment() increases count by 1, triggering the reactive block to log the updated count.let name = 'Alice';
$: {
console.log('Name is ' + Name);
}Name with uppercase 'N', but the variable declared is name lowercase.Name is undefined, causing a runtime error.Name is undefined due to case sensitivity. -> Option BName is undefined due to case sensitivity. [OK]doubleCount automatically whenever count changes, using a reactive block. Which code correctly achieves this?let count = 1; let doubleCount; // Choose the correct reactive block
doubleCount as twice countdoubleCount to count * 2 whenever count changes.doubleCount = count * 2;. $: { doubleCount = count + 2; } adds 2 instead of multiplying. $: doubleCount == count * 2; uses comparison operator == instead of assignment. $: doubleCount = count / 2; divides instead of multiplying.Pass the test and this pattern moves unknown