| | |

Svelte 23 ๐Ÿงก Keyed Each Loops for DOM Reconciliation

โฑ๏ธ Estimated read: 8 min | |

In Svelte, the default behavior of an {#each} block is positional. This means that Svelte tracks items based on their index in the array rather than their actual identity. While this works perfectly for simple, static lists, it becomes problematic as soon as you reorder, filter, or prepend data to your collection. When Svelte only knows about positions, changing the order of your data requires the framework to destroy and recreate the corresponding DOM elements to match the new order.

Keyed loops solve this by associating a unique identifierโ€”a keyโ€”with every item in your collection. When you specify (item.id) in your {#each} loop, you are telling Svelte to track the element by that value forever. If the array is reordered or an item is injected at the start, Svelte can simply move the existing DOM node to the correct position rather than discarding it and constructing a new one. This is known as DOM reconciliation, and it is the bedrock of building performant, stateful, and interactive interfaces.

Key point: Keyed {#each} blocks use unique identifiers to map data items to specific DOM nodes; this ensures that when collections change, Svelte moves or updates existing elements instead of destroying and recreating them, preserving input focus, transition states, and performance.


Why Keyed Loops exist

The state preservation requirement. When you reorder a list without keys, Svelte destroys the DOM nodes. If an input field inside a list item had text typed into it or a checkbox was ticked, that state is lost because the DOM node itself was replaced. Keys prevent this.

The DOM reconciliation efficiency. Constructing and destroying DOM nodes is expensive. By reusing existing nodes, you save browser CPU cycles. Keyed reconciliation ensures the framework only performs the minimum amount of work necessary to match the UI to the data.

The animation stability. If you use Svelteโ€™s built-in transition library (like fly or fade), the transition needs to know that an element is the “same” element even if it moves from index 0 to index 5. Without keys, Svelte cannot track the element across movements, making it impossible to animate reorders smoothly.

The identity mismatch problem. In complex applications, objects are often replaced (e.g., fetching a new state from an API). If you use positional tracking, the UI might flicker or reset scroll positions. Keys provide a persistent identity that survives even when the object references themselves are updated.

The performance scalability. As lists grow largerโ€”think hundreds or thousands of rowsโ€”positional reconciliation becomes a major bottleneck. Reusing elements is not just a feature; it is an architectural necessity for large-scale data grids or long-running stream feeds.


a. Positional vs. Keyed tracking

Positional tracking is Svelteโ€™s default because it is slightly faster for arrays that never change. However, it is almost always the wrong choice for interactive data. When you do not provide a key, Svelte compares index i of the old array to index i of the new array. If the item at index 0 changes, the UI updates. If you swap index 0 and 1, Svelte treats the entire DOM as updated.

<!-- Positional: Svelte tracks by index -->
{#each items as item}
  <Row {item} />
{/each}

A keyed loop changes the lookup from “What is at index i?” to “Where is the node with key x?”. Even if the node with key x moves from the top of the list to the bottom, Svelte finds the existing node and moves it. This preserves the internal state of the component completely.

b. Identity and state preservation

A major benefit of keyed reconciliation is the preservation of component-local state. If your Row component has an internal $state variable (e.g., an “expanded” state for a dropdown), the keyed loop ensures that when the list reorders, the “expanded” state stays attached to the item.

<!-- Keyed: Svelte tracks by id -->
{#each items as item (item.id)}
  <Row {item} />
{/each}

Without the key (item.id), Svelte would simply re-render the components. If row A was expanded and you reordered row B to the top, Svelte would destroy row Aโ€™s component instance and create a new one. The user would see the “expanded” state suddenly vanish or jump to the wrong row because the DOM identity was tied to the position rather than the data.

c. Optimal key selection

Selecting the right key is critical. The key must be unique within the list and stable over time. Using an id generated from a database or a UUID is the gold standard. You should never use the index i as the key if the array can be reordered or filtered, as that effectively turns your keyed loop back into a positional one.

  • Stable: Does the key change when the item changes? It shouldn’t.
  • Unique: Do two items have the same key? They shouldn’t.
  • Simple: Is the key an object? That’s too complex. Use a primitive string or number.

If you are generating keys on the fly, try to keep them tied to the data source. If you must generate a key, ensure the logic is pure and consistent. Using Math.random() as a key is a common mistake; it generates a new key every time the component renders, causing Svelte to destroy and recreate the DOM on every update, defeating the purpose of reconciliation.


Complete Example Session

// ============================================
// PART 1: THE DATA SOURCE
// ============================================
let items = $state([
  { id: 'a', val: 'Apple' },
  { id: 'b', val: 'Banana' }
]);

// ============================================
// PART 2: KEYED ITERATION
// ============================================
<ul>
  {#each items as item (item.id)}
    <li>{item.val}</li>
  {/each}
</ul>

// ============================================
// PART 3: REORDERING LOGIC
// ============================================
function shuffle() {
  items.sort(() => Math.random() - 0.5);
}

// ============================================
// PART 4: THE RECONCILIATION RESULT
// ============================================
// Because we used (item.id), Svelte moves the <li> 
// elements instead of overwriting their text.

The keyed loop ensures that if ‘Apple’ moves, the specific DOM node containing ‘Apple’ is simply reordered in the parent <ul>.


Quick Reference

The Syntax

FormTrackingStability
{#each arr as item}PositionalLow
{#each arr as item (item.id)}KeyedHigh

Keying Requirements

RequirementDescription
UniqueNo two items can share a key
StableKeys must not change for the same data
PrimitiveKeys should be strings or numbers

Best Practices

โœ… Do This:

<!-- Use IDs from your database -->
{#each list as item (item.id)} <li>{item.val}</li> {/each}   // โœ…

<!-- Use simple strings or numbers -->
{#each list as item (item.slug)} ... {/each}                 // โœ…

โŒ Don’t Do This:

<!-- Never use index as a key if order changes -->
{#each list as item, i (i)} ... {/each}                       // โŒ

<!-- Don't use non-deterministic keys -->
{#each list as item (Math.random())} ... {/each}             // โŒ

Common Pitfalls

PitfallWhy It HappensFix
List JitterUsing Math.random() as keyUse fixed ID
State LossUsing positional trackingAdd (item.id)
PerformanceMassive list updatesKeying nodes correctly
Buggy TransitionsElements can’t be trackedKeying nodes correctly

Real-World Examples

1. Todo list with IDs

{#each todos as t (t.id)}<Todo {t} />{/each}

2. User directory

{#each users as u (u.uuid)}<Profile {u} />{/each}

3. Image gallery with stable URLs

{#each images as img (img.url)}<img src={img.url} />{/each}

4. Cart items

{#each cart as item (item.sku)}<CartItem {item} />{/each}

5. Chat messages

{#each msgs as m (m.timestamp)}<ChatBubble {m} />{/each}

6. Dynamic table rows

{#each rows as r (r.db_id)}<tr>...</tr>{/each}

7. Filtered dashboard widgets

{#each widgets as w (w.name)}<Widget {w} />{/each}

8. Breadcrumb navigation

{#each crumbs as c (c.path)}<span>{c.text}</span>{/each}

9. Task kanban board

{#each tasks as t (t.task_id)}<Card {t} />{/each}

10. Multi-step form flow

{#each steps as s (s.step_id)}<Step {s} />{/each}

Visual

Positional Reconciliation (Bad)

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  OLD: [ 1, 2 ]  โ”€โ”€โ–บ  NEW: [ 2, 1 ]   โ”‚
โ”‚  Svelte destroys 1 and 2             โ”‚
โ”‚  Svelte creates 2 and 1              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Keyed Reconciliation (Good)

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  OLD: [ 1(id:a), 2(id:b) ]           โ”‚
โ”‚  NEW: [ 2(id:b), 1(id:a) ]           โ”‚
โ”‚  Svelte detects:                     โ”‚
โ”‚  Move <b> to start                   โ”‚
โ”‚  Move <a> to end                     โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Reconciliation Workflow

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  DATA CHANGE                         โ”‚
โ”‚       โ”‚                              โ”‚
โ”‚       โ–ผ                              โ”‚
โ”‚  LOOKUP EXISTING DOM BY KEY          โ”‚
โ”‚       โ”‚                              โ”‚
โ”‚       โ–ผ                              โ”‚
โ”‚  REORDER/UPDATE/DELETE               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
MechanismKeyed reconciliation
Syntax(item.id)
BenefitState preservation
BottleneckPositional tracking
StabilityHigh

Key takeaways:

  • Identify, don’t position. In any list that changes size or order, always define a unique key to allow Svelte to track items by identity.
  • Save state. Keying components ensures that local component state (like inputs or toggles) persists even when the list order changes.
  • Performance matters. Keyed loops allow Svelte to move DOM nodes rather than recreating them, which is significantly faster and smoother for complex interfaces.
  • Choose stability over simplicity. Never use index or Math.random() as a key if you can avoid it; look for permanent identifiers from your data source.
  • Enable transitions. Keyed blocks are the prerequisite for smooth reorder animations in the Svelte transition system.

Remember: Keyed {#each} loops represent the difference between a UI that feels “rebuilt” and a UI that feels “live.” By explicitly telling Svelte which items are which, you empower the framework to manage your DOM with surgeon-like precision, keeping your application state consistent, your animations fluid, and your performance optimized for the long haul.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!