javascript / intermediate
Snippet
Optimizing Lists with Keyed Each Blocks
When updating a list in Svelte, the framework tries to minimize DOM operations. By providing a unique identifier (a key) in parentheses, Svelte can track specific items even if they are reordered or filtered, instead of just updating the content of existing DOM nodes.
snippet.js
1
2
3
4
5
6
7
8
9
<script>export let users = [];</script><ul>{#each users as user (user.id)}<li>{user.name}</li>{/each}</ul>
svelte
Breakdown
1
{#each users as user (user.id)}
Initializes the loop and defines 'user.id' as the unique key for DOM synchronization.