0
0
SvelteHow-ToBeginner · 4 min read

How to Use Runes in Svelte 5: Syntax and Examples

In Svelte 5, runes are special reactive blocks that let you run code reactively when dependencies change. Use the {#rune name} block with a name and reactive statements inside to create them. They help organize reactive logic cleanly within your component.
📐

Syntax

The basic syntax for a rune in Svelte 5 uses the {#rune name} block, where name is an identifier for the rune. Inside this block, you write reactive code that runs whenever its dependencies update.

Example parts:

  • {#rune myRune}: starts the rune block named myRune
  • Reactive statements inside run automatically when needed
  • {/rune}: closes the rune block
svelte
<script>
  let count = 0;
</script>

{#rune myRune}
  console.log('Count changed:', count);
{/rune}
Output
Count changed: 0 Count changed: 1 Count changed: 2 (each time count changes)
💻

Example

This example shows a rune that reacts to a counter variable and logs its value whenever it changes. It also updates a message displayed in the UI.

svelte
<script>
  let count = 0;
  let message = '';
</script>

<button on:click={() => count++}>Increment</button>
<p>{message}</p>

{#rune updateMessage}
  message = `Current count is ${count}`;
{/rune}
Output
Button labeled 'Increment' and a paragraph showing 'Current count is 0' initially, updating each click to 'Current count is 1', 'Current count is 2', etc.
⚠️

Common Pitfalls

Common mistakes when using runes include:

  • Not naming the rune block, which causes syntax errors.
  • Trying to use runes for non-reactive code; runes only run when dependencies change.
  • Modifying variables inside runes without proper reactive declarations, which can cause unexpected behavior.

Always ensure your rune has a unique name and only contains reactive logic.

svelte
<script>
  let count = 0;
</script>

<!-- Wrong: unnamed rune block -->
{#rune}
  console.log(count);
{/rune}

<!-- Right: named rune block -->
{#rune logCount}
  console.log(count);
{/rune}
Output
Syntax error for unnamed rune; logs count correctly for named rune.
📊

Quick Reference

Rune SyntaxDescription
{#rune name} ... {/rune}Defines a reactive rune block named 'name'
Reactive statementsCode inside runs when dependencies change
Unique nameEach rune must have a unique identifier
Use for reactive logicIdeal for side effects and derived state
Cannot be unnamedOmitting the name causes errors

Key Takeaways

Use {#rune name} blocks to create reactive code that runs when dependencies change.
Always give your rune a unique name to avoid syntax errors.
Runes help organize side effects and reactive logic cleanly inside Svelte components.
Avoid using runes for non-reactive or static code.
Update variables reactively inside runes to keep UI and logic in sync.