0
0
Svelteframework~5 mins

Keyed each blocks in Svelte

Choose your learning style9 modes available
Introduction

Keyed each blocks help Svelte track list items by a unique key. This makes updating lists smoother and faster.

When rendering a list of items that can change order or be added/removed
When you want to keep input focus or animations on list items during updates
When you want to avoid unnecessary re-rendering of unchanged list elements
Syntax
Svelte
{#each items as item (item.id)}
  <!-- content -->
{/each}

The part in parentheses (item.id) is the unique key for each item.

Keys should be unique and stable for each item to work well.

Examples
Loop through users and use user.id as the key.
Svelte
{#each users as user (user.id)}
  <p>{user.name}</p>
{/each}
Use task.taskId as the unique key for each task.
Svelte
{#each tasks as task (task.taskId)}
  <li>{task.title}</li>
{/each}
When items are simple values like numbers, use the value itself as the key.
Svelte
{#each numbers as number (number)}
  <span>{number}</span>
{/each}
Sample Program

This Svelte component shows a list of fruits. When you click the button, the list order changes randomly. Using a keyed each block with fruit.id helps Svelte update the list efficiently without losing track of each fruit.

Svelte
<script>
  let fruits = [
    { id: 1, name: 'Apple' },
    { id: 2, name: 'Banana' },
    { id: 3, name: 'Cherry' }
  ];

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

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

<ul>
  {#each fruits as fruit (fruit.id)}
    <li>{fruit.name}</li>
  {/each}
</ul>
OutputSuccess
Important Notes

Always use a unique and stable key to avoid bugs.

If you don't use keys, Svelte will update list items by position, which can cause unexpected behavior.

Keys help with animations and preserving input states inside list items.

Summary

Keyed each blocks use a unique key to track list items.

This improves list updates and keeps UI consistent.

Use keys whenever your list can change dynamically.