Svelte 5 reactivity with runes: $state, $derived, $effect, $props and $inspect, shared state in .svelte.ts modules, and when stores still fit.
.cursor/rules/svelte-reactivity-patterns.mdc. Downloaded files need to be placed in that repository path.---
description: "Svelte 5 reactivity with runes: $state, $derived, $effect, $props and $inspect, shared state in .svelte.ts modules, and when stores still fit."
globs: "**/*"
alwaysApply: false
---
Apply these rules to Svelte components. They target Svelte 5 runes mode; check the project's Svelte version before using them.
## Runes
- `$state` for reactive local values. Objects and arrays declared with `$state` are deeply reactive, so `items.push(x)` updates the UI.
- `$derived` for values computed from other state (`let total = $derived(price * qty)`); use `$derived.by(() => { ... })` for multi-line logic. Derived values are recalculated when their dependencies change; do not compute them in `$effect`.
- `$effect` only for side effects that synchronize with something outside Svelte (DOM APIs, timers, analytics, subscriptions). Return a cleanup function when the effect sets something up.
- `$props()` for component inputs, and `$bindable()` for props the parent may bind to.
- `$inspect(value)` logs a value whenever it changes during development; it is removed from production builds.
```svelte
<script lang="ts">
type Item = { name: string; price: number };
let { items }: { items: Item[] } = $props();
let query = $state('');
let visible = $derived(
items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase()))
);
let total = $derived(visible.reduce((sum, item) => sum + item.price, 0));
$inspect(query);
</script>
<input bind:value={query} placeholder="Filter items" />
<p>{visible.length} items, total {total}</p>
```
## Shared state
- Share reactive state between components from a `.svelte.ts` / `.svelte.js` module. Export an object and mutate its properties (a reassigned exported `$state` variable is not reactive for importers):
```ts
// cart.svelte.ts
export const cart = $state({ items: [] as string[] });
export function addToCart(id: string) {
cart.items.push(id);
}
```
- In SvelteKit, module-level state is shared by every request on the server. Keep per-user data in `load` results, `event.locals` or component context, not in module state.
## Stores
- Stores (`writable`, `readable`, `derived` from `svelte/store`) still work. Use them for values produced outside components over time (WebSocket feeds, browser APIs) or in code that must also work with Svelte 4. A custom store is any object with a `subscribe` method that follows the store contract.
## Async values
- Render promises with `{#await promise}...{:then value}...{:catch error}...{/await}`, or load data in SvelteKit `load` functions instead of fetching in `$effect`.
## Legacy syntax
- In legacy (Svelte 4 style) components, `$:` statements, `export let` and `on:click` still work. Do not mix them with runes in the same component; when you migrate a component, convert it fully (`npx sv migrate svelte-5` helps).
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.
Cursor
frontend
Illustrative input and expected result. This example is a verification guide, not a recorded model run.
Content reviewed .
A Svelte 5 product list uses $: statements for the filtered list and a writable store for a cart that only components read and update.
Apply the Svelte Reactivity Patterns rule to src/lib/components/ProductList.svelte and src/lib/stores/cart.ts (Svelte 5, SvelteKit 2).
ProductList uses $props, $state for the query and $derived for the filtered list and total; the cart moves to cart.svelte.ts exporting a $state object with mutating helpers; no $effect computes derived values; the answer warns against keeping per-user cart data in module state on the server.
Cursor applies project rules stored as .mdc files in .cursor/rules. Each rule's frontmatter (description, globs, alwaysApply) decides whether it is always included, attached to matching files, chosen by the agent from its description, or only used when you @-mention it. Cursor also reads AGENTS.md in the project root and subdirectories for plain-Markdown instructions.
.cursor/rules/svelte-reactivity-patterns.mdcStarting point, not a tested configuration for your repository. Attached when files matching the globs are in context (alwaysApply: false with globs). Review the instructions, adapt the file paths and run your project's existing checks.
---
description: "Svelte Reactivity Patterns project conventions"
globs: "**/*"
alwaysApply: false
---
Apply these rules to Svelte components. They target Svelte 5 runes mode; check the project's Svelte version before using them.
## Runes
- `$state` for reactive local values. Objects and arrays declared with `$state` are deeply reactive, so `items.push(x)` updates the UI.
- `$derived` for values computed from other state (`let total = $derived(price * qty)`); use `$derived.by(() => { ... })` for multi-line logic. Derived values are recalculated when their dependencies change; do not compute them in `$effect`.
- `$effect` only for side effects that synchronize with something outside Svelte (DOM APIs, timers, analytics, subscriptions). Return a cleanup function when the effect sets something up.
- `$props()` for component inputs, and `$bindable()` for props the parent may bind to.
- `$inspect(value)` logs a value whenever it changes during development; it is removed from production builds.
```svelte
<script lang="ts">
type Item = { name: string; price: number };
let { items }: { items: Item[] } = $props();
let query = $state('');
let visible = $derived(
items.filter((item) => item.name.toLowerCase().includes(query.toLowerCase()))
);
let total = $derived(visible.reduce((sum, item) => sum + item.price, 0));
$inspect(query);
</script>
<input bind:value={query} placeholder="Filter items" />
<p>{visible.length} items, total {total}</p>
```
## Shared state
- Share reactive state between components from a `.svelte.ts` / `.svelte.js` module. Export an object and mutate its properties (a reassigned exported `$state` variable is not reactive for importers):
```ts
// cart.svelte.ts
export const cart = $state({ items: [] as string[] });
export function addToCart(id: string) {
cart.items.push(id);
}
```
- In SvelteKit, module-level state is shared by every request on the server. Keep per-user data in `load` results, `event.locals` or component context, not in module state.
## Stores
- Stores (`writable`, `readable`, `derived` from `svelte/store`) still work. Use them for values produced outside components over time (WebSocket feeds, browser APIs) or in code that must also work with Svelte 4. A custom store is any object with a `subscribe` method that follows the store contract.
## Async values
- Render promises with `{#await promise}...{:then value}...{:catch error}...{/await}`, or load data in SvelteKit `load` functions instead of fetching in `$effect`.
## Legacy syntax
- In legacy (Svelte 4 style) components, `$:` statements, `export let` and `on:click` still work. Do not mix them with runes in the same component; when you migrate a component, convert it fully (`npx sv migrate svelte-5` helps).
Ask for a small change to one matching file. Check the tool's loaded context or instruction view, inspect the diff for the requested convention, and run the relevant build or test. A well-formatted file does not guarantee the model follows every instruction.
Cursor's docs recommend keeping individual rules under 500 lines and splitting large rules into composable ones. Cursor's documentation states that it supports AGENTS.md in the project root and in subdirectories. Use AGENTS.md for plain-Markdown instructions you also want other tools to read, and .mdc rules when you need Cursor's scoping options (globs, description-based selection, always-apply).
Documentation checked 2026-11-05: Cursor docs: Rules
Cursor rules for Next.js 14+ App Router projects updated for Next.js 16 with async params, validated Route Handlers, generateMetadata and proxy.ts in place of middleware.
Cursor rules for strict TypeScript: compiler checks beyond strict, interfaces vs type aliases, real type guards, discriminated unions, utility types and branded IDs.
Cursor rules for Tailwind CSS v4: automatic class sorting, mobile-first breakpoints, CVA variants with merging, class-based dark mode via @custom-variant, and CSS-first @theme configuration.