Description
I'm a new Svelte user, and I am currently going through the tutorial in an attempt to learn the basics of Svelte. I've just finished tinkering with the "Keyed each blocks" tutorial and I found that the explanation for why the tutorial's proposed solution works is practically nonexistent, or at the very least, lacking.
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 rather than remove the last one and update all the others.To do that, we specify a unique key for each iteration of the
each
block:/// file: App.svelte {#each things as thing (+++thing.id+++)} <Thing name={thing.name}/> {/each}[!NOTE] 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.
I find that personally, even though this explanation makes it clear that adding a key separates each iteration and makes them uniquely identifiable, I personally cannot gather from the explanation the way that this changes the behavior of the Array.shift method used in the tutorial, or why/how the addition of a key would affect the need to re-render the DOM elements in the each loop.