0 day streak
javascript / beginner
Snippet

Optimizing DOM List Reconciliations with Unique Keys in Svelte

Supplying a unique key in parentheses after the each block iterator tells Svelte how to track individual list elements. This enables efficient DOM reuse and preserves element-specific state during additions, removals, or re-ordering operations.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
<script>
let tasks = [
{ id: 101, text: 'Inspect telemetry' },
{ id: 102, text: 'Refactor styles' }
];
</script>
<ul>
{#each tasks as task (task.id)}
<li>{task.text}</li>
{/each}
</ul>
svelte
Breakdown
1
{#each tasks as task (task.id)}
Iterates through the tasks collection while tagging each DOM fragment with the unique task.id key.
2
<li>{task.text}</li>
Renders an individual list entry that can be precisely patched by Svelte's diffing engine.
3
{/each}
Closes the keyed iteration block.