Skip to main content
Key blocks destroy and recreate their contents when the value of an expression changes. This is useful for forcing components to reinitialize or triggering transitions.

Basic Syntax

Reinitializing Components

When used around components, key blocks cause them to be reinstantiated and reinitialized:

Example: Resetting Component State

Triggering Transitions

Key blocks are useful for playing transitions whenever a value changes:

Example: Animated Counter

Real-World Use Cases

Route Transitions

Data Refresh

Media Player

Animated Messages

Resetting Form State

Key blocks are perfect for resetting forms without manually clearing each field:

Dynamic Component Switching

Performance Considerations

Key blocks completely destroy and recreate their contents. This means:
  • All component state is lost
  • DOM elements are removed and recreated
  • Lifecycle methods run again
Use key blocks intentionally, not as a default pattern.

When to Use Key Blocks

  • Force a component to reset to its initial state
  • Trigger enter/exit transitions on value changes
  • Ensure media elements reload with new sources
  • Reset complex third-party components

When NOT to Use Key Blocks

  • Simple value updates (use reactive statements instead)
  • List rendering (use {#each} with keys)
  • Conditional rendering (use {#if} blocks)
  • Minor UI updates

Combining with Other Blocks