Performance: Why reactivity drives UI updates
This concept affects how quickly the UI updates in response to data changes, impacting interaction responsiveness and visual stability.
let count = 0; $: doubled = count * 2; function increment() { count++; } <!-- In markup --> <p id="count">{count}</p> <p>Doubled: {doubled}</p>
let count = 0; function increment() { count++; // Manually update DOM elements or force full component re-render document.getElementById('count').textContent = count; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual DOM updates on data change | Multiple direct DOM writes | Multiple reflows per update | High paint cost due to layout thrashing | [X] Bad |
| Svelte reactive variables with $: syntax | Minimal DOM updates only where needed | Single reflow per update | Low paint cost with efficient batching | [OK] Good |
let to declare reactive variables at the top level. Reassigning them triggers automatic UI updates.let count = 0; declares a reactive variable. var $count = 0; and const count = reactive(0); are invalid syntax. $: doubled = count * 2; is a reactive statement for derived values.let count = 0; -> Option Alet [OK]let declares reactive variables [OK]$: is required for basic variablesreactive() or $varlet count = 1;
$: doubled = count * 2;
<button on:click={() => count++}>Increment</button>
<p>Doubled: {doubled}</p>count changes?let count = 0;
function increment() {
count = count + 1;
}
<button on:click={increment}>Add</button>
<p>Count: {count}</p>let are reactive by default when reassigned.on:click={increment} syntax is correct, and {count} will update when count changes.$: is needed for all variables$: label allows creating reactive variables that update automatically when dependencies change.$: selectedCount = items.filter(i => i.selected).length; ensures selectedCount updates whenever items or their selected property changes.Pass the test and this pattern moves unknown