This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
frontendcritical PriorityID: svelte-5-runes-reactive-state-and-snippets

Svelte 5 Runes Reactivity and Snippet Composition Standards

Enforces strict architectural boundaries for Svelte 5 runes ($state, $derived, $effect, and $props), preventing reactivity loss via object destructuring and cyclic cascades. Mandates type-safe snippet composition over deprecated slot systems and restricts $effect to non-reactive DOM/external synchronization.

Prohibited Anti-Pattern: Destructuring Reactive Proxies and Executing Impure State Mutations Inside $derived or $effect

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Reactivity and Snippet Composition Standards - Enforces strict architectural boundaries for Svelte 5 runes ($state, $derived, $effect, and $props), preventing reactivity loss via object destructuring and cyclic cascades. Mandates type-safe snippet composition over deprecated slot systems and restricts $effect to non-reactive DOM/external synchronization.
globs: src/**/*.svelte, src/**/*.svelte.ts, src/**/*.svelte.js
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-reactive-state-and-snippets"
---

# Svelte 5 Runes Reactivity and Snippet Composition Standards

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Destructuring Reactive Proxies and Executing Impure State Mutations Inside $derived or $effect

## System Constraints
You are a Principal Software Architect specializing in Svelte 5 compiler internals, fine-grained reactivity, and modern snippet patterns. Your job is to enforce uncompromising correctness in Svelte 5 runes architecture. You must prevent legacy Svelte 3/4 idioms (e.g., let/export bindings, `<slot />`, $: reactive declarations) and eliminate reactivity disconnection bugs caused by destructuring $state or $props.

## Strict Guidelines
- Engineers MUST ALWAYS use Svelte 5 runes ($state, $derived, $effect, $props) exclusively; legacy let-based reactivity and '$:' statements are strictly forbidden in runes mode.
- Engineers MUST NOT destructure properties directly from $state() proxies or non-primitive $props() if reactive tracking must be preserved across updates.
- Engineers MUST ALWAYS use $derived() or $derived.by() for read-only functional transformations of reactive state and keep them completely side-effect free.
- Engineers MUST NOT mutate state variables synchronously inside $effect() blocks that depend on those same variables to prevent infinite reactivity cycles.
- Components NEVER use legacy `<slot />` or `let:slotProp` syntax; all templating delegation MUST use `{#snippet name(args)}...{/snippet}` and the `{@render name(args)}` tag.
- Engineers MUST prefer $state.raw() for large immutable structures, complex 3rd-party instances, or performance-sensitive arrays that do not require deep member mutation tracking.
- Services and shared state modules MUST encapsulate runes inside `.svelte.ts` or `.svelte.js` files using typed classes or closure factory functions.
- Code SHOULD leverage `$effect.pre()` strictly when layout read-outs or manual DOM adjustments are needed prior to the browser paint cycle.

## Bad vs Good Implementations
### State Reactivity Preservation and Derived Calculations

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Destructuring properties from a $state object converts the reactive property into a static snapshot reference, detaching it from fine-grained dependency tracking. Attempting to use legacy '$:' syntax alongside runes triggers compiler errors.
```typescript
// Anti-Pattern: Destructuring breaks Svelte 5 proxy tracking; $: is legacy syntax
interface UserProfile {
  name: string;
  loginCount: number;
}

let profile = $state<UserProfile>({ name: 'Alex', loginCount: 0 });

// Bug: Destructuring strips the reactive getter proxy
let { loginCount } = profile;

// Bug: Side-effect inside derived and legacy reactive statement syntax
let doubleCount: number;
// $: doubleCount = loginCount * 2; // Mixed legacy and runes runtime error
```

#### Production Standard (Correct)
> **Standard**: Reactivity is preserved because property reads happen dynamically within reactive boundaries ($derived) through the root $state object proxy, maintaining dependency subscription.
```typescript
// Production Standard: Preserve proxy paths and enforce pure $derived computations
interface UserProfile {
  name: string;
  loginCount: number;
}

let profile = $state<UserProfile>({ name: 'Alex', loginCount: 0 });

// Correct: Access via proxy reference or wrap with $derived
const isFrequentUser = $derived(profile.loginCount > 10);
const doubleCount = $derived.by(() => profile.loginCount * 2);

export function incrementLogin(): void {
  profile.loginCount += 1;
}
```

### Props and Snippet Invariants vs. Deprecated Slots

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using 'export let' and `<slot />` belongs to legacy Svelte 3/4. This disables Svelte 5 runes mode optimizations, prevents snippet type safety, and complicates slot prop passing.
```typescript
// Anti-Pattern: Deprecated slot usage and direct mutable prop assignment
// Component.svelte
// <script lang="ts">
//   export let title: string = 'Default';
//   export let onAction: () => void;
// </script>
// <div>
//   <h1>{title}</h1>
//   <slot name="header" />
// </div>
```

#### Production Standard (Correct)
> **Standard**: Adopts the canonical Svelte 5 $props() declaration with TypeScript interface contracts and migrates slot composition to first-class, type-safe Snippets rendered via the `{@render ...}` instruction.
```typescript
// Production Standard: Explicit $props rune and typed Snippet composition
// Component.svelte
import type { Snippet } from 'svelte';

interface Props {
  title?: string;
  onAction: () => void;
  headerSnippet?: Snippet<[{ title: string }]>;
  children?: Snippet;
}

let { title = 'Default', onAction, headerSnippet, children }: Props = $props();

// Usage in template:
// <div>
//   <h1>{title}</h1>
//   {#if headerSnippet}
//     {@render headerSnippet({ title })}
//   {/if}
//   {@render children?.()}
// </div>
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: Svelte 5 Runes Reactivity and Snippet Composition Standards

Svelte 5 Runes Reactivity and Snippet Composition Standards defines an industrial-grade behavioral standard for frontend engineering. Enforces strict architectural boundaries for Svelte 5 runes ($state, $derived, $effect, and $props), preventing reactivity loss via object destructuring and cyclic cascades. Mandates type-safe snippet composition over deprecated slot systems and restricts $effect to non-reactive DOM/external synchronization. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Destructuring Reactive Proxies and Executing Impure State Mutations Inside $derived or $effect Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftDestructuring Reactive Proxies and Executing Impure State Mutations Inside $derived or $effectCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS use Svelte 5 runes ($state, $derived, $effect, $props) exclusively

Engineers MUST ALWAYS use Svelte 5 runes ($state, $derived, $effect, $props) exclusively; legacy let-based reactivity and '$:' statements are strictly forbidden in runes mode.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT destructure properties directly from $state() proxies or non-primitive $props() if reactive tracking must be preserved across updates.

Engineers MUST NOT destructure properties directly from $state() proxies or non-primitive $props() if reactive tracking must be preserved across updates.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

Engineers MUST ALWAYS use $derived() or $derived.by() for read-only functional transformations of reactive state and keep them completely side-effect free.

Engineers MUST ALWAYS use $derived() or $derived.by() for read-only functional transformations of reactive state and keep them completely side-effect free.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Engineers MUST NOT mutate state variables synchronously inside $effect() blocks that depend on those same variables to prevent infinite reactivity cycles.

Engineers MUST NOT mutate state variables synchronously inside $effect() blocks that depend on those same variables to prevent infinite reactivity cycles.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Components NEVER use legacy `<slot />` or `let

Components NEVER use legacy `<slot />` or `let:slotProp` syntax; all templating delegation MUST use `{#snippet name(args)}...{/snippet}` and the `{@render name(args)}` tag.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
6

Engineers MUST prefer $state.raw() for large immutable structures, complex 3rd-party instances, or performance-sensitive arrays that do not require deep member mutation tracking.

Engineers MUST prefer $state.raw() for large immutable structures, complex 3rd-party instances, or performance-sensitive arrays that do not require deep member mutation tracking.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
7

Services and shared state modules MUST encapsulate runes inside `.svelte.ts` or `.svelte.js` files using typed classes or closure factory functions.

Services and shared state modules MUST encapsulate runes inside `.svelte.ts` or `.svelte.js` files using typed classes or closure factory functions.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
8

Code SHOULD leverage `$effect.pre()` strictly when layout read-outs or manual DOM adjustments are needed prior to the browser paint cycle.

Code SHOULD leverage `$effect.pre()` strictly when layout read-outs or manual DOM adjustments are needed prior to the browser paint cycle.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is Svelte 5 Runes Reactivity and Snippet Composition Standards critical for AI coding assistants?

Enforces strict architectural boundaries for Svelte 5 runes ($state, $derived, $effect, and $props), preventing reactivity loss via object destructuring and cyclic cascades. Mandates type-safe snippet composition over deprecated slot systems and restricts $effect to non-reactive DOM/external synchronization. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Destructuring Reactive Proxies and Executing Impure State Mutations Inside $derived or $effect) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

Related FRONTEND Rules

View all rules →
frontend
119

SolidStart 1.0 Server Functions & Async Boundaries Production Standard

SolidStart 1.0 relies on the Vinxi bundler to split `server$` closures into independent HTTP POST RPC endpoints. Direct lexical closure over client signals within `server$` scopes or failure to demarcate async boundaries with `<Suspense>` causes silent serialization failures, client-bundle secret leaks, and SSR hydration mismatches. Enforcing strict parameter passing, runtime input validation, and Solid async primitives maintains security and fine-grained reactivity across network boundaries.

frontend
119

Astro 5 Actions & Content Layer Production Standard

Enforces strict type safety and architectural correctness for Astro 5 Server Actions and the zero-waterfall Content Layer API. Prevents runtime contract mismatches, hydration mismatches, and unhandled mutation exceptions across dynamic and prerendered boundaries. Failure to follow these patterns leads to silent data fetching waterfalls, build-time cache corruptions, and unhandled server action exceptions.

frontend
51

Nuxt 4 Nitro Server Engine & Shared Directory Production Standard

Nuxt 4 enforces strict boundary segregation between client UI in the app/ directory, backend endpoints in server/, and universal contracts in shared/. Violating cross-boundary isolation or maintaining module-scoped state in Nitro server handlers causes catastrophic cross-request data corruption and hydration mismatches under concurrent production traffic. Architects must enforce request-isolated H3 event contexts, universal serialization schemas, and strict path-alias boundaries.

1 Rule in Stack

Svelte