Basic Svelte
Introduction
Bindings
Advanced Svelte
Advanced reactivity
Motion
Advanced bindings
Advanced transitions
Context API
Special elements
<script module>
Next steps
Basic SvelteKit
Introduction
Routing
Loading data
Headers and cookies
Shared modules
API routes
Stores
Errors and redirects
Advanced SvelteKit
Page options
Link options
Advanced routing
Advanced loading
Environment variables
Conclusion
By default, when you modify the value of an each
block, it will add and remove DOM nodes at the end of the block, and update any values that have changed. That might not be what you want.
It’s easier to show why than to explain. Inside Thing.svelte
, name
is a dynamic prop but emoji
is a constant.
Click the ‘Remove first thing’ button a few times, and notice what happens:
- It removes the last component.
- It then updates the
name
value in the remaining DOM nodes, but not the emoji.
If you’re coming from React, this might seem strange, because you’re used to the entire component re-rendering when state changes. Svelte works differently: the component ‘runs’ once, and subsequent updates are ‘fine-grained’. This makes things faster and gives you more control.
One way to fix it would be to make emoji
a $derived
value. But it makes more sense to remove the first <Thing>
component altogether than to remove the last one and update all the others.
To do that, we specify a unique key for each iteration of the each
block:
{#each things as thing (thing.id)}
<Thing name={thing.name}/>
{/each}
You can use any object as the key, as Svelte uses a
Map
internally — in other words you could do(thing)
instead of(thing.id)
. Using a string or number is generally safer, however, since it means identity persists without referential equality, for example when updating with fresh data from an API server.
<script>
import Thing from './Thing.svelte';
let things = $state([
{ id: 1, name: 'apple' },
{ id: 2, name: 'banana' },
{ id: 3, name: 'carrot' },
{ id: 4, name: 'doughnut' },
{ id: 5, name: 'egg' }
]);
</script>
<button onclick={() => things.shift()}>
Remove first thing
</button>
{#each things as thing}
<Thing name={thing.name} />
{/each}