0 day streak
javascript / beginner
Snippet

Improving Rendering Performance with Keyed Each Blocks

By supplying a unique key expression like (item.id) in an each block, Svelte can identify exactly which DOM elements have changed, moved, or been removed. This avoids recreating existing DOM nodes and significantly enhances rendering performance.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
let items = [
{ id: 'item-101', name: 'Keyboard', price: 79 },
{ id: 'item-102', name: 'Mouse', price: 49 },
{ id: 'item-103', name: 'Monitor', price: 199 }
];
function removeItem(targetId) {
items = items.filter(item => item.id !== targetId);
}
</script>
<ul>
{#each items as item (item.id)}
<li>
<span>{item.name} - ${item.price}</span>
<button on:click={() => removeItem(item.id)}>Remove</button>
</li>
{/each}
</ul>
svelte
Breakdown
1
{#each items as item (item.id)}
Specifies a unique identifier (item.id) as the key to optimize DOM diffing and element recycling.
2
items = items.filter(item => item.id !== targetId);
Triggers Svelte reactivity by assigning a new array filtered by the unique identifier.