0
0
Svelteframework~15 mins

Each blocks ({#each}) in Svelte - Deep Dive

Choose your learning style9 modes available
Overview - Each blocks ({#each})
What is it?
Each blocks in Svelte are a way to repeat a piece of the user interface for every item in a list or array. They let you write a template once and show it multiple times, once per item. This helps display lists like menus, tables, or any repeated content easily. The syntax uses {#each} to start and {/each} to end the block.
Why it matters
Without each blocks, developers would have to manually write repeated code for every item, which is slow, error-prone, and hard to maintain. Each blocks automate this repetition, making apps dynamic and responsive to changing data. This means users see up-to-date lists without extra work from developers, improving user experience and developer productivity.
Where it fits
Before learning each blocks, you should understand basic Svelte syntax and how to create components. After mastering each blocks, you can learn about keyed each blocks for better performance, and advanced list handling like filtering and sorting in Svelte.
Mental Model
Core Idea
Each blocks repeat a chunk of UI for every item in a list, automatically creating one copy per item.
Think of it like...
Imagine a cookie cutter stamping the same shape repeatedly on dough. Each block is like the cookie cutter, and the dough is your list of items. Each stamp creates one cookie, just like each block creates one UI piece per item.
List of items
  ↓
{#each} block
  ├─ UI for item 1
  ├─ UI for item 2
  ├─ UI for item 3
  └─ ...
{/each}

This repeats UI for every item in the list.
Build-Up - 7 Steps
1
FoundationBasic syntax of each blocks
🤔
Concept: Learn the simple structure of an each block to repeat UI for list items.
In Svelte, you write {#each items as item} to start the block and {/each} to end it. Inside, you use {item} to show each element. For example:
    {#each fruits as fruit}
  • {fruit}
  • {/each}
Result
The browser shows a bulleted list with apple, banana, and cherry each in its own list item.
Understanding the basic syntax unlocks the power to dynamically create UI elements from any list, making your app flexible and data-driven.
2
FoundationUsing index in each blocks
🤔
Concept: Learn how to access the position of each item in the list during iteration.
You can get the current item's index by adding a second variable after the item name: {#each items as item, index}. For example:
    {#each fruits as fruit, i}
  • {i + 1}: {fruit}
  • {/each}
Result
The list shows numbered fruits: 1: apple, 2: banana, 3: cherry.
Knowing the index lets you add numbering or special styles based on position, enhancing UI clarity and user experience.
3
IntermediateKeyed each blocks for performance
🤔Before reading on: do you think Svelte always re-renders the entire list when data changes, or only the changed items? Commit to your answer.
Concept: Learn how to tell Svelte which item uniquely identifies each element to optimize updates.
By default, Svelte reuses DOM elements but can get confused if list items change order or content. You can add a key to each block like {#each items as item (item.id)} where item.id is unique. This helps Svelte track items and update only what changed. Example:
    {#each users as user (user.id)}
  • {user.name}
  • {/each}
Result
When users change order or update, only the affected list items update in the DOM, improving performance.
Understanding keys prevents unnecessary DOM changes, making apps faster and smoother, especially with large or dynamic lists.
4
IntermediateConditional content inside each blocks
🤔Before reading on: can you put if-else conditions inside each blocks to show different UI per item? Commit to your answer.
Concept: Learn to combine each blocks with if blocks to customize UI per item.
Inside an each block, you can use {#if} to show different content based on item properties. For example:
    {#each tasks as task (task.id)}
  • {#if task.done} {task.text} {:else} {task.text} {/if}
  • {/each}
Result
Tasks that are done appear crossed out, others normal, all in a list.
Combining each with if blocks lets you build rich, dynamic lists that respond to data states, enhancing interactivity.
5
IntermediateNested each blocks for complex lists
🤔
Concept: Learn how to use each blocks inside each blocks to handle lists within lists.
If your data has nested arrays, you can nest each blocks. For example, a list of categories each with items:
    {#each categories as category}
  • {category.name}
      {#each category.items as item}
    • {item}
    • {/each}
  • {/each}
Result
A nested list showing categories with their items below each.
Nested each blocks allow you to represent complex data structures naturally in the UI.
6
AdvancedReactive updates in each blocks
🤔Before reading on: do you think changing the array inside a script automatically updates the UI inside each blocks, or do you need extra code? Commit to your answer.
Concept: Learn how Svelte reacts to changes in arrays and updates each blocks automatically.
Svelte tracks changes to reactive variables. When you modify an array (like adding or removing items), the each block updates the UI automatically. For example:
    {#each todos as todo}
  • {todo}
  • {/each}
Result
Clicking the button adds a new task to the list shown on screen immediately.
Knowing Svelte's reactivity model helps you write clean code that updates UI without manual DOM manipulation.
7
ExpertHandling list mutations and keys pitfalls
🤔Before reading on: do you think using non-unique or changing keys in each blocks causes bugs or performance issues? Commit to your answer.
Concept: Understand subtle bugs and performance traps when keys are missing, duplicated, or unstable in each blocks.
If keys are missing or not unique, Svelte may reuse DOM elements incorrectly, causing UI glitches like wrong item updates or flickers. Also, if keys change between renders, Svelte destroys and recreates elements unnecessarily. Example of a bad key: {#each items as item (item.name)} If item.name is not unique or changes, problems occur. Best practice: use stable, unique IDs that never change. {#each items as item (item.id)}
{item.name}
{/each}
Result
UI updates correctly without flicker or wrong data shown when keys are stable and unique.
Understanding key stability prevents subtle bugs and improves app performance, crucial for professional Svelte apps.
Under the Hood
Svelte compiles each blocks into JavaScript code that creates, updates, and removes DOM elements based on the array data. It tracks the list items and their keys to know which DOM nodes correspond to which data items. When the array changes, Svelte compares old and new lists using keys to update only the necessary DOM parts, avoiding full re-renders.
Why designed this way?
This design lets Svelte produce highly efficient code that updates the UI with minimal work. Unlike frameworks that do heavy runtime diffing, Svelte shifts this work to compile time and uses keys to optimize updates. This approach reduces browser work and improves app speed and responsiveness.
Data array → Compiler → Generated JS code
      ↓                      ↓
  {#each} block         DOM create/update/remove
      ↓                      ↓
  Keys track items → Efficient DOM patching

This flow shows how Svelte turns each blocks into fast DOM updates.
Myth Busters - 4 Common Misconceptions
Quick: Does Svelte re-render the entire list every time any item changes? Commit yes or no.
Common Belief:Svelte always re-renders the whole list inside an each block when data changes.
Tap to reveal reality
Reality:Svelte uses keys and smart DOM updates to only change the parts of the list that actually changed.
Why it matters:Believing full re-renders happen leads to unnecessary performance worries and bad optimization attempts.
Quick: Can you use any value as a key in each blocks without issues? Commit yes or no.
Common Belief:Any property can be used as a key in each blocks, even if it changes or is not unique.
Tap to reveal reality
Reality:Keys must be unique and stable; changing or duplicate keys cause UI bugs and performance problems.
Why it matters:Using bad keys leads to flickering UI, wrong data shown, or wasted rendering, frustrating users and developers.
Quick: Can you put if blocks inside each blocks to customize each item’s UI? Commit yes or no.
Common Belief:You cannot use if blocks inside each blocks; they must be separate.
Tap to reveal reality
Reality:You can freely nest if blocks inside each blocks to conditionally render different UI per item.
Why it matters:Knowing this enables building rich, dynamic lists that respond to item states, improving user experience.
Quick: Does Svelte automatically update the UI when you mutate an array without reassigning it? Commit yes or no.
Common Belief:Changing an array in place (like push) automatically updates the UI inside each blocks.
Tap to reveal reality
Reality:Svelte only tracks reactive assignments; mutating arrays without reassigning does not trigger updates.
Why it matters:Misunderstanding this causes confusing bugs where UI does not update, wasting developer time.
Expert Zone
1
Keys should be stable across renders; even if the data changes, the key must not change to avoid DOM thrashing.
2
Using indexes as keys is acceptable only for static lists that never reorder or change length; otherwise, it causes subtle bugs.
3
Svelte’s compiler optimizes each blocks by generating minimal DOM operations, but complex nested each blocks can still impact performance.
When NOT to use
Each blocks are not suitable for rendering very large lists with thousands of items; in such cases, use virtual scrolling libraries or pagination to improve performance.
Production Patterns
In real apps, each blocks are combined with stores for reactive data, keyed properly for smooth updates, and often paired with transitions for animated list changes.
Connections
React map function
Similar pattern of rendering lists by mapping data to UI elements.
Understanding Svelte each blocks helps grasp React’s map rendering, showing how frameworks handle dynamic lists differently.
Database indexing
Keys in each blocks are like indexes in databases that uniquely identify records for fast lookup and updates.
Knowing how keys optimize UI updates is like understanding how indexes speed up database queries, both improving efficiency.
Assembly line manufacturing
Each block’s repeated UI creation is like an assembly line producing identical parts efficiently.
Seeing UI rendering as an assembly line clarifies how repetition and optimization work together in software and manufacturing.
Common Pitfalls
#1Using array index as key for dynamic lists that reorder or change length.
Wrong approach:{#each items as item, i (i)}
{item.name}
{/each}
Correct approach:{#each items as item (item.id)}
{item.name}
{/each}
Root cause:Misunderstanding that indexes change when list order changes, causing wrong DOM reuse.
#2Mutating array without reassigning to trigger UI update.
Wrong approach:todos.push('New task'); // no reassignment
Correct approach:todos = [...todos, 'New task']; // reassignment triggers update
Root cause:Not knowing Svelte tracks reactive assignments, not mutations.
#3Omitting keys in lists that reorder or update dynamically.
Wrong approach:{#each users as user}
  • {user.name}
  • {/each}
    Correct approach:{#each users as user (user.id)}
  • {user.name}
  • {/each}
    Root cause:Assuming keys are optional even when list changes, leading to UI bugs.
    Key Takeaways
    Each blocks let you repeat UI for every item in a list easily and dynamically.
    Keys uniquely identify items to help Svelte update only what changed, improving performance.
    You can combine each blocks with if blocks and nesting for rich, complex lists.
    Svelte’s reactivity requires reassigning arrays to trigger UI updates inside each blocks.
    Using stable, unique keys and understanding reactivity prevents common bugs and ensures smooth user experiences.