Performance: tick function
The tick function affects how updates are batched and when the DOM reflects state changes, impacting rendering speed and interaction smoothness.
import { tick } from 'svelte'; let count = 0; async function increment() { count++; await tick(); const height = document.getElementById('box').offsetHeight; console.log(height); }
import { afterUpdate } from 'svelte'; let count = 0; function increment() { count++; // Immediately query DOM here const height = document.getElementById('box').offsetHeight; console.log(height); } // Using afterUpdate causes code to run after every update, not just this one
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using afterUpdate for DOM reads | Multiple reads after every update | Multiple forced reflows | High paint cost due to layout thrashing | [X] Bad |
| Using tick to await DOM update | Single read after update | Single reflow per update | Lower paint cost, smoother rendering | [OK] Good |
tick function in Svelte?tick doestick function waits for Svelte to complete DOM updates after state changes.tick's purpose.tick inside a Svelte component?tick is usedtick returns a Promise and must be awaited inside an async function.await tick(); inside an async function. Others misuse tick as a normal function or callback.import { tick } from 'svelte';
let count = 0;
async function increment() {
count += 1;
await tick();
console.log(document.getElementById('count').textContent);
}increment() is called?count, then waits for DOM update with await tick().import { tick } from 'svelte';
let name = 'Alice';
function updateName() {
name = 'Bob';
tick();
console.log(document.getElementById('name').textContent);
}tick to achieve this?await tick() after pushing the item, ensuring DOM updates before focusing.Pass the test and this pattern moves unknown