0
0
Svelteframework~8 mins

Keyed each blocks in Svelte - Performance & Optimization

Choose your learning style9 modes available
Performance: Keyed each blocks
HIGH IMPACT
This affects how efficiently the browser updates the DOM when lists change, impacting rendering speed and visual stability.
Rendering a list of items that can change dynamically
Svelte
<script>
  let items = [1, 2, 3];
</script>

{#each items as item (item)}
  <div>{item}</div>
{/each}
Keys let Svelte track each item uniquely, updating only changed elements and preserving DOM stability.
📈 Performance GainReduces reflows to only changed items, minimizing layout shifts and improving user experience.
Rendering a list of items that can change dynamically
Svelte
<script>
  let items = [1, 2, 3];
</script>

{#each items as item}
  <div>{item}</div>
{/each}
Without keys, Svelte may reuse DOM nodes incorrectly, causing unnecessary re-renders and layout shifts.
📉 Performance CostTriggers multiple reflows and repaints on list updates, causing noticeable layout shifts (high CLS).
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Unkeyed each blockRecreates or reorders many DOM nodesMultiple reflows per updateHigh paint cost due to layout shifts[X] Bad
Keyed each blockUpdates only changed DOM nodesSingle or minimal reflowsLow paint cost with stable layout[OK] Good
Rendering Pipeline
When using keyed each blocks, Svelte compares keys to update only necessary DOM nodes, reducing layout recalculations and repaints.
Layout
Paint
Composite
⚠️ BottleneckLayout stage due to unnecessary DOM node replacements without keys
Core Web Vital Affected
CLS
This affects how efficiently the browser updates the DOM when lists change, impacting rendering speed and visual stability.
Optimization Tips
1Always provide a unique key for each item in Svelte each blocks.
2Keys help minimize DOM node replacements and layout recalculations.
3Reducing layout shifts improves user experience and CLS scores.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main benefit of using keys in Svelte each blocks?
AIt helps Svelte update only changed items, reducing layout shifts.
BIt makes the list render faster by skipping JavaScript execution.
CIt increases bundle size but improves CSS performance.
DIt disables reactivity for the list items.
DevTools: Performance
How to check: Record a performance profile while updating the list, then inspect the Layout and Paint events to see how many reflows and repaints occur.
What to look for: Look for fewer Layout and Paint events with keyed each blocks, indicating less layout thrashing and better visual stability.