{#key}
The {#key value} block re-creates its contents whenever value changes. Useful for resetting state, animating route changes, and forcing fresh DOM.
Svelte — key block
EXAMPLE
<script>
let mode = 'list';
let selected = 0;
</script>
<!-- ===== Basic syntax ===== -->
{#key mode}
<Page mode={mode} />
{/key}
<!-- Whenever 'mode' changes, the contents are torn down + rebuilt. -->
<!-- Without key: state inside Page persists across mode changes (might be wrong). -->
<!-- ===== Reset child state on selection change ===== -->
<button on:click={() => selected = 1}>Show #1</button>
<button on:click={() => selected = 2}>Show #2</button>
{#key selected}
<UserCard userId={selected} />
{/key}
<!-- Each time 'selected' changes, UserCard starts fresh:
- useState() (Svelte stores) re-initialised
- <input> values reset
- lifecycle hooks (onMount) re-run
-->
<!-- ===== Pair with transitions ===== -->
<script>
import { fade } from 'svelte/transition';
</script>
{#key selected}
<div in:fade out:fade>
<UserCard userId={selected} />
</div>
{/key}
<!-- ===== Pair with await for live data ===== -->
{#key route}
{#await loadData(route)}
<p>Loading...</p>
{:then data}
<Result {data} />
{:catch err}
<p>Error: {err.message}</p>
{/await}
{/key}
<!-- ===== Force a component remount per id ===== -->
<!-- Common for routers: tearing down + bringing up a Profile page per :id -->
{#each Object.keys(pages) as id (id)}
<a href={'/profile/' + id}>Profile {id}</a>
{/each}
{#key $page.params.id}
<ProfilePage id={$page.params.id} />
{/key}
<!-- ===== Pitfalls =====
- Wrapping LARGE subtrees in {#key} -> heavy teardown / setup on every change
- Using a key that changes too often -> constant rebuilds, perf hit
- Forgetting that #each already has its own keying syntax (each {x} (id))
- Expecting #key to preserve state — it does the OPPOSITE
-->
<!-- ===== Patterns to internalise =====
- {#key id} per route segment when nav should reset the page
- {#key value} around transition blocks to retrigger animation
- Pair with {#await} when the data fetch depends on the key
- Use sparingly; wide #key blocks have a real cost
-->
Why it matters
{#key value} is the explicit "reset this subtree when this changes" tool. Pairs cleanly with transitions and route changes. Reach for it when persistence is the wrong default — usually when the URL or identity beneath changes.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
{#key value}
<Component /> <!-- destroy + recreate when value changes -->
{/key}
Try it Yourself »
Discussion
Loading…