javascript / intermediate
Snippet
Triggering Rerenders with the Key Block
The {#key} block destroys and recreates its content whenever the value of the expression changes. This is particularly useful for re-triggering transitions on an element that stays in the DOM or for completely resetting a component's internal state when a specific ID changes.
snippet.js
javascript
1
2
3
4
5
{#key uniqueId}<div in:fly={{ y: 20 }} out:fade><ComplexComponent data={currentData} /></div>{/key}
svelte
Breakdown
1
{#key uniqueId}
Tells Svelte to watch 'uniqueId'. When it changes, the entire block is remounted.
2
in:fly={{ y: 20 }}
Since the element is recreated, the entry transition runs every time uniqueId updates.