Performance: Each blocks ({#each})
This affects how many DOM nodes are created and updated during rendering, impacting page load and interaction speed.
<script> import { onMount } from 'svelte'; let items = []; let visibleCount = 20; onMount(() => { items = Array(1000).fill(0).map((_, i) => i); }); </script> <ul> {#each items.slice(0, visibleCount) as item} <li>{item}</li> {/each} </ul>
<script> let items = Array(1000).fill(0).map((_, i) => i); </script> <ul> {#each items as item} <li>{item}</li> {/each} </ul>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Render all items at once | 1000 nodes created | 1000 reflows | High paint cost | [X] Bad |
| Render limited items with slice | 20 nodes created | 20 reflows | Low paint cost | [OK] Good |
{#each} block do in Svelte?{#each}{#each} block is used to repeat content for every item in a list or array.{#each} = repeat list items [OK]{#each} loops over lists [OK]{#each} with {#if}items and display each item in Svelte?{#each array as item} to loop over an array.{#each items as item} <p>{item}</p> {/each} uses as correctly. Options A, B, and C use incorrect keywords.as keyword in {#each} [OK]{`
<ul>?fruit for the item and i for the index starting at 0.0: apple, 1: banana, 2: cherry.{`
number as the item, but inside the block it uses {num}, which is undefined.{#each} with keys in Svelte?user.id.{#each users as user (user.id)} <p>{user.name}</p> {/each} uses user.id as key, which is best. {#each users as user} <p>{user.name}</p> {/each} has no key, less efficient. {#each users as user (user.name)} <p>{user.name}</p> {/each} uses user.name, which may not be unique. {#each users as user (index)} <p>{user.name}</p> {/each} uses index, which can cause issues when list changes.Pass the test and this pattern moves unknown