0
0
Svelteframework~3 mins

Why Keyed each blocks in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if your list could update instantly without losing what you typed or causing flickers?

The Scenario

Imagine you have a list of items on a webpage, like a to-do list, and you want to update it when items change or move around.

You try to update the list by removing and adding items manually in the code every time something changes.

The Problem

Manually updating each item is slow and confusing.

You might accidentally remove the wrong item or lose the user's input in a form inside the list.

The page can flicker or reset unexpectedly, making a bad experience.

The Solution

Keyed each blocks in Svelte let the framework track each item by a unique key.

This means Svelte only updates the items that actually changed, keeping the rest intact.

It makes updates smooth, fast, and keeps user input safe.

Before vs After
Before
{#each items as item}
  <li>{item.name}</li>
{/each}
After
{#each items as item (item.id)}
  <li>{item.name}</li>
{/each}
What It Enables

It enables smooth, efficient updates of lists that keep user input and animations intact.

Real Life Example

Think of a chat app where messages can be edited or deleted.

Keyed each blocks let the app update only the changed messages without flickering or losing scroll position.

Key Takeaways

Manual list updates are slow and error-prone.

Keyed each blocks track items by unique keys for smart updates.

This keeps the UI smooth and user-friendly.