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

Svelte 5 Runes Reactive State, Derived Tracking, and Snippet Composition Invariants

Svelte 5 replaces legacy compile-time variable instrumentation with runtime fine-grained reactive proxies governed by runes ($state, $derived, $effect, $props). Developers must never simulate computed state using side-effectful $effect synchronization, never destructure $state objects into plain local primitives, and eliminate legacy slots in favor of typed snippet closures.

Prohibited Anti-Pattern: Simulating Computed State with $effect and Severing Reactivity via Proxy Destructuring

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: Svelte 5 Runes Reactive State, Derived Tracking, and Snippet Composition Invariants - Svelte 5 replaces legacy compile-time variable instrumentation with runtime fine-grained reactive proxies governed by runes ($state, $derived, $effect, $props). Developers must never simulate computed state using side-effectful $effect synchronization, never destructure $state objects into plain local primitives, and eliminate legacy slots in favor of typed snippet closures.
globs: src/**/*.{svelte,svelte.ts,svelte.js,ts}
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/svelte-5-runes-reactivity-snippets-standard"
---

# Svelte 5 Runes Reactive State, Derived Tracking, and Snippet Composition Invariants

> **Severity**: CRITICAL | **Category**: frontend
> **Anti-Pattern Warning**: Simulating Computed State with $effect and Severing Reactivity via Proxy Destructuring

## System Constraints
You are a Principal Software Architect specializing in Svelte 5 application architecture. Your task is to enforce strict invariants around Svelte 5 Runes ($state, $derived, $effect, $props) and Snippet components. Ensure fine-grained reactive graphs are deterministic, eliminate unnecessary effect cycles, protect reactive proxies from destructive destructuring, and eradicate legacy Svelte 3/4 syntax.

## Strict Guidelines
- Engineers MUST ALWAYS use `$derived(expr)` or `$derived.by(() => fn)` for computed values, NEVER synchronizing state manually across `$state` variables inside an `$effect`.
- Engineers MUST NOT destructure properties directly from a `$state` object into local variables, as this decouples the value from the reactive proxy and freezes tracking.
- Components NEVER use legacy `<slot />` or `let:binding` syntax; all slot-like dynamic templating MUST be modeled via `{#snippet name(args)}` blocks and rendered using `{@render name(args)}`.
- Components MUST declare their interface using `let { prop1, prop2 = default }: Props = $props();` instead of legacy `export let` syntax.
- Code MUST reserve `$effect` strictly for external browser interactions, imperative subscriptions, or DOM mutations, and MUST return a cleanup callback whenever listeners or intervals are allocated.
- Services MUST use `.svelte.ts` file extensions whenever authoring shared classes or domain models that instantiate `$state` or `$derived` runes outside `.svelte` single-file components.

## Bad vs Good Implementations
### Synchronizing Computed Values: $effect Anti-pattern vs $derived Invariant

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Using an $effect to write to another $state variable violates pure reactive data flow, triggers secondary execution cycles, and causes microtask thrashing.
```typescript
// Anti-pattern: Simulating computed values with $effect causes multiple render passes and race conditions
let count = $state(0);
let double = $state(0);

$effect(() => {
  // Re-triggers dependency loops and invalidates fine-grained batching
  double = count * 2;
});
```

#### Production Standard (Correct)
> **Standard**: The $derived rune cleanly models pure relational state with zero side-effects, re-evaluating only when downstream consumers read the tracked proxy.
```typescript
// Invariant: Derived values are pure, lazily evaluated, and synchronously tracked dependencies
let count = $state(0);
const double = $derived(count * 2);
```

### Component Decomposition: Legacy Slots vs Svelte 5 Snippets and Typed Props

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: Legacy export let and slot directives circumvent Svelte 5 fine-grained runtime proxy optimizations and prevent strict TypeScript typing on transcluded templates.
```svelte
<!-- Anti-pattern: Svelte 3/4 legacy export let and slot projections -->
<script lang="ts">
  export let items: string[];
</script>

<ul>
  {#each items as item}
    <li>
      <slot name="item" row={item}>
        <span>{item}</span>
      </slot>
    </li>
  {/each}
</ul>
```

#### Production Standard (Correct)
> **Standard**: Using $props with typed Snippet closures allows compiler validation, fine-grained DOM patching, and deterministic parameter passing.
```svelte
<!-- Invariant: Svelte 5 $props with typed Snippets and {@render} -->
<script lang="ts">
  import type { Snippet } from 'svelte';

  interface Props {
    items: string[];
    itemTemplate?: Snippet<[item: string]>;
  }

  let { items, itemTemplate }: Props = $props();
</script>

<ul>
  {#each items as item (item)}
    <li>
      {#if itemTemplate}
        {@render itemTemplate(item)}
      {:else}
        <span>{item}</span>
      {/if}
    </li>
  {/each}
</ul>
```

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 Reactive State, Derived Tracking, and Snippet Composition Invariants

Svelte 5 Runes Reactive State, Derived Tracking, and Snippet Composition Invariants defines an industrial-grade behavioral standard for frontend engineering. Svelte 5 replaces legacy compile-time variable instrumentation with runtime fine-grained reactive proxies governed by runes ($state, $derived, $effect, $props). Developers must never simulate computed state using side-effectful $effect synchronization, never destructure $state objects into plain local primitives, and eliminate legacy slots in favor of typed snippet closures. 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: Simulating Computed State with $effect and Severing Reactivity via Proxy Destructuring 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 DriftSimulating Computed State with $effect and Severing Reactivity via Proxy DestructuringCritical
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 `$derived(expr)` or `$derived.by(() => fn)` for computed values, NEVER synchronizing state manually across `$state` variables inside an `$effect`.

Engineers MUST ALWAYS use `$derived(expr)` or `$derived.by(() => fn)` for computed values, NEVER synchronizing state manually across `$state` variables inside an `$effect`.

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 a `$state` object into local variables, as this decouples the value from the reactive proxy and freezes tracking.

Engineers MUST NOT destructure properties directly from a `$state` object into local variables, as this decouples the value from the reactive proxy and freezes 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.
3

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

Components NEVER use legacy `<slot />` or `let:binding` syntax; all slot-like dynamic templating MUST be modeled via `{#snippet name(args)}` blocks and rendered using `{@render name(args)}`.

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

Components MUST declare their interface using `let { prop1, prop2 = default }

Components MUST declare their interface using `let { prop1, prop2 = default }: Props = $props();` instead of legacy `export let` syntax.

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

Code MUST reserve `$effect` strictly for external browser interactions, imperative subscriptions, or DOM mutations, and MUST return a cleanup callback whenever listeners or intervals are allocated.

Code MUST reserve `$effect` strictly for external browser interactions, imperative subscriptions, or DOM mutations, and MUST return a cleanup callback whenever listeners or intervals are allocated.

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

Services MUST use `.svelte.ts` file extensions whenever authoring shared classes or domain models that instantiate `$state` or `$derived` runes outside `.svelte` single-file components.

Services MUST use `.svelte.ts` file extensions whenever authoring shared classes or domain models that instantiate `$state` or `$derived` runes outside `.svelte` single-file components.

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 Reactive State, Derived Tracking, and Snippet Composition Invariants critical for AI coding assistants?

Svelte 5 replaces legacy compile-time variable instrumentation with runtime fine-grained reactive proxies governed by runes ($state, $derived, $effect, $props). Developers must never simulate computed state using side-effectful $effect synchronization, never destructure $state objects into plain local primitives, and eliminate legacy slots in favor of typed snippet closures. 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 (Simulating Computed State with $effect and Severing Reactivity via Proxy Destructuring) 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