0
0
SvelteHow-ToBeginner · 3 min read

How to Use Key in Each Block in Svelte for Efficient Updates

In Svelte, use each blocks with a key to uniquely identify list items for efficient DOM updates. The syntax is {#each items as item (item.id)}, where item.id is the unique key for each element.
📐

Syntax

The key in an each block tells Svelte which property uniquely identifies each item. This helps Svelte update only changed items instead of re-rendering the whole list.

Syntax parts:

  • {#each items as item}: loops over items.
  • (item.id): the unique key for each item.
  • {/each}: ends the loop.
svelte
{#each items as item (item.id)}
  <p>{item.name}</p>
{/each}
💻

Example

This example shows a list of users rendered with a key based on their unique id. When the list changes, Svelte updates only the affected user elements.

svelte
<script>
  let users = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Carol' }
  ];

  function shuffle() {
    users = users
      .map(value => ({ value, sort: Math.random() }))
      .sort((a, b) => a.sort - b.sort)
      .map(({ value }) => value);
  }
</script>

<button on:click={shuffle}>Shuffle Users</button>

{#each users as user (user.id)}
  <p>{user.name}</p>
{/each}
Output
Button labeled 'Shuffle Users' and below it a list of user names: Alice, Bob, Carol in random order after clicking the button.
⚠️

Common Pitfalls

Common mistakes when using key in Svelte's each block include:

  • Using a non-unique or changing value as the key, which can cause incorrect DOM updates.
  • Omitting the key, which makes Svelte recreate all list items on every update, hurting performance.
  • Using the array index as a key, which is discouraged because it breaks when items reorder.

Always use a stable, unique property like an id.

svelte
<!-- Wrong: using index as key -->
{#each items as item, index (index)}
  <p>{item.name}</p>
{/each}

<!-- Right: using unique id as key -->
{#each items as item (item.id)}
  <p>{item.name}</p>
{/each}
📊

Quick Reference

Key points for using key in each blocks:

  • Use a unique, stable property for the key (e.g., item.id).
  • Do not use array indexes as keys.
  • Keys help Svelte update only changed items efficiently.
  • Syntax: {#each items as item (item.id)}.

Key Takeaways

Always provide a unique and stable key in Svelte each blocks to optimize DOM updates.
Avoid using array indexes as keys because they can cause incorrect UI behavior on reorder.
The key syntax is {#each items as item (item.id)} where item.id uniquely identifies each element.
Using keys helps Svelte update only changed list items, improving performance and UI consistency.