0 day streak
javascript / expert
Snippet

Optimizing DOM Reconciliation with Keyed Each Blocks

Providing a unique identifier (key) in an #each block allows Svelte's diffing algorithm to track individual elements. This prevents unnecessary DOM re-renders and preserves local component state during sorting or filtering.

snippet.js
javascript
1
2
3
4
5
6
7
8
<!-- High-performance list rendering -->
{#each items as item (item.id)}
<div class="row">
<Component {item} />
</div>
{:else}
<p>No items found.</p>
{/each}
svelte
Breakdown
1
(item.id)
The 'key' expression that tells Svelte how to uniquely identify each item in the collection.
2
<Component {item} />
Because of the key, this component instance is reused rather than destroyed and recreated when the list order changes.
3
{:else}
Provides a fallback UI state when the array is empty, improving the user experience.