0
0
Svelteframework~8 mins

tick function in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: tick function
MEDIUM IMPACT
The tick function affects how updates are batched and when the DOM reflects state changes, impacting rendering speed and interaction smoothness.
Waiting for DOM updates before running code
Svelte
import { tick } from 'svelte';

let count = 0;

async function increment() {
  count++;
  await tick();
  const height = document.getElementById('box').offsetHeight;
  console.log(height);
}
tick waits for the DOM to update only after this change, batching updates and avoiding extra reflows.
📈 Performance Gainsingle reflow per update, smoother interaction
Waiting for DOM updates before running code
Svelte
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
Using afterUpdate runs code after every component update, causing unnecessary DOM reads and potential layout thrashing.
📉 Performance Costtriggers multiple reflows if updates are frequent
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Using afterUpdate for DOM readsMultiple reads after every updateMultiple forced reflowsHigh paint cost due to layout thrashing[X] Bad
Using tick to await DOM updateSingle read after updateSingle reflow per updateLower paint cost, smoother rendering[OK] Good
Rendering Pipeline
The tick function schedules code to run after Svelte flushes DOM updates, ensuring the browser has applied changes before reading layout.
Update Scheduling
Layout
Paint
⚠️ BottleneckLayout (reflow) caused by reading DOM properties too early
Core Web Vital Affected
INP
The tick function affects how updates are batched and when the DOM reflects state changes, impacting rendering speed and interaction smoothness.
Optimization Tips
1Use tick to wait for DOM updates before reading layout properties.
2Avoid reading DOM properties immediately after state changes to prevent forced reflows.
3Batch DOM reads and writes to reduce layout thrashing and improve interaction responsiveness.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using Svelte's tick function?
AIt prevents any DOM updates from happening
BIt immediately forces the browser to repaint
CIt batches DOM updates and delays code until after the DOM is updated
DIt increases the number of reflows for accuracy
DevTools: Performance
How to check: Record a performance profile while interacting with the component. Look for layout thrashing or multiple forced reflows in the flame chart.
What to look for: Fewer layout events and shorter long tasks indicate better use of tick for batching updates.