Frontend · Nov 25, 2026 · 13 min read

Svelte 5 Runes: Hands-On Patterns for $state, $derived, $effect

Complete tutorial showing exactly how to use Svelte 5 runes in real applications, with concrete code examples, migration steps from stores, TypeScript patterns, SvelteKit integration, and production t

Svelte 5 Runes: Hands-On Patterns for $state, $derived, $effect

Why the Reactivity Model Changed in Svelte 5

Svelte 5 introduces runes as explicit primitives for reactivity. The previous model relied on the compiler analyzing assignments to top-level let variables and the $: label for derived values. This approach worked well for small components but created hidden dependencies that were difficult to reason about in larger applications.

Runes make reactivity visible and intentional. $state(), $derived(), and $effect() declare exactly what should be reactive. The compiler no longer needs to scan every assignment, resulting in faster compilation and more predictable runtime behavior. This change aligns Svelte with signals-based frameworks while keeping its component model intact.

Runes are opt-in for Svelte 4 projects via a configuration flag, but they are the default behavior for new Svelte 5 projects. The transition requires understanding a few core functions and adjusting how you think about state, but the payoff is clearer code and fewer surprising updates.

Creating a Svelte 5 Project

Start by running the official scaffolding command:

npm create svelte@latest my-svelte5-app

Choose the Skeleton project template, enable TypeScript, add ESLint and Prettier when prompted. After installation, navigate into the directory and run npm install.

To explicitly enable runes (required for Svelte 4 compatibility or specific configurations), update svelte.config.js:

import { vitePreprocess } from '@sveltejs/vite-plugin-svelte';

export default {
  preprocess: vitePreprocess(),
  compilerOptions: {
    runes: true
  }
};

Run npm run dev to start the development server. The project now uses the runes-based reactivity system. All new components will declare props, state, and effects using the rune functions instead of the old export let and $: syntax.

Using $state for Reactive Data

The $state rune creates a reactive value that triggers updates when its properties change. Unlike Svelte 4's let with assignment detection, $state uses proxies under the hood for granular tracking.

Basic counter example:

<script lang="ts">
  let count = $state(0);

  function increment() {
    count += 1; // This update is tracked automatically
  }
</script>

<button on:click={increment}>
  Count: {count}
</button>

For objects and arrays, $state tracks mutations at the property and index level:

<script lang="ts">
  interface Task {
    id: number;
    text: string;
    done: boolean;
  }

  let tasks = $state<Task[]>([
    { id: 1, text: 'Learn runes', done: false }
  ]);

  function addTask(text: string) {
    tasks.push({
      id: Date.now(),
      text,
      done: false
    });
    // No need to reassign the array - mutation is tracked
  }

  function toggleDone(id: number) {
    const task = tasks.find(t => t.id === id);
    if (task) task.done = !task.done;
  }
</script>

This granular tracking avoids unnecessary re-renders of components that only depend on specific properties. In Svelte 4, mutating an object often required creating a new reference with the spread operator to guarantee an update. That boilerplate is now unnecessary.

Trade-off: $state objects are always proxied. For very large data structures (tens of thousands of objects), the proxy overhead can be measured. In those cases, consider keeping raw data outside of $state and only wrapping the parts that drive the UI.

Computed Values with $derived

The $derived rune creates values that automatically update when their dependencies change. It replaces both the $: label and derived stores from previous versions.

<script lang="ts">
  let items = $state([
    { price: 12.5, quantity: 3 },
    { price: 8.0, quantity: 7 }
  ]);

  let total = $derived(
    items.reduce((sum, item) => sum + item.price * item.quantity, 0)
  );

  let expensiveItems = $derived(
    items.filter(item => item.price > 10)
  );
</script>

<p>Total: ${total.toFixed(2)}</p>
<p>Expensive items: {expensiveItems.length}</p>

Multiple levels of derivation are supported and only recalculate when necessary. The Svelte compiler analyzes the dependency graph statically, so $derived values that depend on other derived values update in the correct order without extra work from the developer.

Important distinction from Svelte 4: $derived only depends on values that are explicitly referenced inside the function. Reading a value inside a condition still registers it as a dependency. This is more predictable than the old heuristic-based approach.

Use $derived.by when you need to run more complex logic with early returns or multiple statements:

let status = $derived.by(() => {
  if (total > 100) return 'large';
  if (total > 30) return 'medium';
  return 'small';
});

Side Effects with $effect

$effect replaces most uses of onMount, afterUpdate, and reactive statements that caused side effects. The effect runs after the DOM has been updated.

<script lang="ts">
  let count = $state(0);

  $effect(() => {
    // Runs after every update to count
    document.title = `Count is ${count}`;
    
    // Cleanup function returned from effect
    return () => {
      console.log('Cleaning up previous effect');
    };
  });
</script>

For effects that should run before the DOM updates, use $effect.pre:

$effect.pre(() => {
  // Useful for measuring DOM elements before paint
  console.log('Before browser paint');
});

Common production use cases include persisting state to localStorage, setting up WebSocket subscriptions, and syncing with external libraries like Leaflet maps or Chart.js.

Example integrating with the browser Clipboard API:

<script lang="ts">
  let copied = $state(false);
  let text = $state('Share this link');

  $effect(() => {
    if (copied) {
      const timeout = setTimeout(() => {
        copied = false;
      }, 2000);
      return () => clearTimeout(timeout);
    }
  });
</script>

Warning: avoid updating state that the effect itself depends on inside the effect body. This creates infinite loops. Svelte 5 logs a clear warning when it detects such cycles.

Declaring Component Props with $props

The $props rune replaces export let. It provides better TypeScript support and clearer intent.

<script lang="ts">
  const { name, age = 30, onSave } = $props<{
    name: string;
    age?: number;
    onSave?: (data: any) => void;
  }>();
</script>

<h1>Hello {name}</h1>

Children are accessed via the children property when destructuring. For forwarded events or actions, the new syntax is more explicit than the old $$props and $$restProps.

Migrating from Svelte 4 Stores to Runes

Most applications using Svelte 4 rely heavily on writable, readable, and derived stores from svelte/store. These can be replaced directly with runes for simpler mental models.

Before (Svelte 4):

<script>
  import { writable, derived } from 'svelte/store';
  
  export const count = writable(0);
  export const doubled = derived(count, $count => $count * 2);
</script>

After (Svelte 5 runes):

<script lang="ts">
  // In a shared state file or context
  export function createCounter() {
    let count = $state(0);
    let doubled = $derived(count * 2);
    
    function increment() {
      count += 1;
    }
    
    return { count, doubled, increment };
  }
</script>

For global state shared across the entire app, you can create a module that exports a state factory or use Svelte's new context runes ($context and setContext with runes-based objects).

Migration checklist:

  • Replace writable() with $state()
  • Replace derived() with $derived()
  • Move side effects from subscribe() callbacks into $effect()
  • Update component bindings from bind:value={$store} to direct value={state} since state is no longer a store
  • Remove autoSubscribe imports and $store prefix usage

Applications with dozens of stores typically see a reduction in boilerplate code by 30-40% after migration, though exact savings depend on architecture.

Building a Task Management Application

Let's implement a realistic task manager to demonstrate all three core runes working together. The app supports adding tasks, marking complete, filtering, and persisting to localStorage.

First, the root +page.svelte in a SvelteKit project:

<script lang="ts">
  interface Task {
    id: string;
    title: string;
    completed: boolean;
    createdAt: Date;
  }

  let tasks = $state<Task[]>([]);
  let filter = $state<'all' | 'active' | 'completed'>('all');
  let newTaskTitle = $state('');

  // Load from localStorage
  $effect(() => {
    const saved = localStorage.getItem('tasks');
    if (saved) {
      tasks = JSON.parse(saved).map((t: any) => ({
        ...t,
        createdAt: new Date(t.createdAt)
      }));
    }
  });

  // Persist to localStorage whenever tasks change
  $effect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks));
  });

  let visibleTasks = $derived(() => {
    if (filter === 'active') return tasks.filter(t => !t.completed);
    if (filter === 'completed') return tasks.filter(t => t.completed);
    return tasks;
  });

  function addTask() {
    if (!newTaskTitle.trim()) return;
    
    tasks.unshift({
      id: crypto.randomUUID(),
      title: newTaskTitle.trim(),
      completed: false,
      createdAt: new Date()
    });
    
    newTaskTitle = '';
  }

  function toggleTask(id: string) {
    const task = tasks.find(t => t.id === id);
    if (task) task.completed = !task.completed;
  }

  function deleteTask(id: string) {
    tasks = tasks.filter(t => t.id !== id);
  }
</script>

<main>
  <input bind:value={newTaskTitle} placeholder="New task..." />
  <button on:click={addTask}>Add</button>
  
  <div>
    <button on:click={() => filter = 'all'}>All</button>
    <button on:click={() => filter = 'active'}>Active</button>
    <button on:click={() => filter = 'completed'}>Completed</button>
  </div>
  
  <ul>
    {#each visibleTasks as task (task.id)}
      <li class:completed={task.completed}>
        <input type="checkbox" checked={task.completed} 
               on:change={() => toggleTask(task.id)} />
        {task.title}
        <button on:click={() => deleteTask(task.id)}>Delete</button>
      </li>
    {/each}
  </ul>
  
  <p>{tasks.filter(t => !t.completed).length} tasks remaining</p>
</main>

This single-file implementation demonstrates several production patterns: localStorage synchronization via $effect, derived filtering that only recomputes when tasks or filter changes, and direct mutation of state objects without extra boilerplate.

For larger applications, extract the task logic into a separate composable function that returns an object containing all state and methods. This pattern is the Svelte 5 equivalent of a custom store.

Advanced State Composition and Context

When applications grow beyond a few components, sharing state via props becomes cumbersome. Svelte 5 provides improved context APIs that work naturally with runes.

Create a context provider component:

<!-- TaskProvider.svelte -->
<script lang="ts">
  import { setContext } from 'svelte';

  let tasks = $state<Task[]>([]);
  // ... all the logic from previous example

  setContext('tasks', {
    tasks,
    addTask,
    toggleTask,
    deleteTask,
    visibleTasks
  });
</script>

<slot />

Consume in child components:

<script lang="ts">
  import { getContext } from 'svelte';
  
  const { tasks, toggleTask } = getContext<any>('tasks');
</script>

This pattern avoids prop drilling while maintaining fine-grained reactivity. Only components that actually read specific pieces of state re-render when those pieces change.

For even more complex state, consider integrating with existing state management libraries that expose signals or compatible reactive primitives. However, for most mid-sized applications, the built-in runes plus context provide sufficient power without additional dependencies.

Integrating with SvelteKit Loaders and Server Data

SvelteKit 2.0+ works seamlessly with Svelte 5. Server-loaded data can be passed to runes-based components:

<!-- +page.server.ts -->
export async function load({ fetch }) {
  const res = await fetch('/api/tasks');
  const tasks = await res.json();
  return { tasks };
}

In the page component, initialize state from server data:

<script lang="ts">
  let { data } = $props<{ data: { tasks: Task[] } }>();
  let tasks = $state(data.tasks);
</script>

Subsequent mutations remain client-side. For optimistic updates with server synchronization, combine $effect with fetch calls or use SvelteKit's form actions for progressive enhancement.

Testing Components Built with Runes

Testing remains straightforward with Vitest and @testing-library/svelte. The reactive nature of runes is handled automatically by the testing environment.

Example test for the task component:

import { render, screen, fireEvent } from '@testing-library/svelte';
import { describe, it, expect } from 'vitest';
import TaskManager from './TaskManager.svelte';

describe('TaskManager', () => {
  it('adds a new task when form is submitted', async () => {
    render(TaskManager);
    
    const input = screen.getByPlaceholderText('New task...');
    await fireEvent.input(input, { target: { value: 'Write tests' } });
    
    const button = screen.getByText('Add');
    await fireEvent.click(button);
    
    expect(screen.getByText('Write tests')).toBeInTheDocument();
  });

  it('marks task as completed', async () => {
    render(TaskManager);
    // ... additional setup with initial tasks
    const checkbox = screen.getByRole('checkbox');
    await fireEvent.click(checkbox);
    
    expect(screen.getByText('1 task remaining')).toBeInTheDocument();
  });
});

Because $state and $derived update synchronously in tests, assertions can be made immediately after events. For effects that involve timers or async operations, use vi.useFakeTimers() to keep tests deterministic.

Production Optimizations and Trade-offs

Runes enable better tree-shaking and smaller JavaScript payloads because the compiler can see exactly which values are reactive. However, overusing $derived for values that change frequently can cause more updates than necessary.

Best practices observed in production applications:

  • Keep $state objects as flat as possible for easier debugging
  • Use $derived for filter and sort operations rather than recomputing them in templates
  • Extract expensive calculations into Web Workers and update state with results via $effect
  • Profile with the Svelte devtools browser extension to see which runes cause the most updates
  • For lists of hundreds of items, consider virtual scrolling libraries that integrate cleanly with $state arrays

When deploying, SvelteKit's adapter-static, adapter-node, or adapter-cloudflare all work without special configuration for runes. The production build automatically strips development-only code from effects and derived values.

Memory usage of proxied $state objects is slightly higher than plain objects. In applications dealing with very large datasets (50,000+ items), store the canonical data outside of runes and derive only the visible slice. This hybrid approach gives the best balance of developer experience and runtime performance.

Browser support is identical to Svelte 4 — the compiled output is vanilla JavaScript that runs on any modern browser. No new polyfills are required.

Debugging and Developer Experience

Svelte 5 ships improved debugging tools. The $inspect rune lets you log reactive values with additional metadata:

$inspect(tasks).with((value) => {
  console.log('Tasks updated:', value.length);
});

Combined with the official Svelte browser devtools extension, you can see the dependency graph between runes in real time. This makes performance debugging significantly easier than tracing implicit dependencies in Svelte 4.

Error messages are more specific when you accidentally create dependency cycles or try to update state during a render phase. The compiler also warns about potential performance issues such as creating new functions or objects inside $derived on every run.

Future-Proofing Applications Built with Runes

By adopting runes now, your components will remain compatible with future Svelte releases. The Svelte team has stated that the runes model is the foundation for upcoming features including fine-grained reactivity in server components and improved hydration strategies.

Many community libraries have already updated to support both the legacy mode and runes mode. When choosing new packages, prefer those that expose composable functions returning $state objects rather than relying exclusively on stores.

The transition period between Svelte 4 and Svelte 5 will likely last 12-18 months in the ecosystem. Applications that incrementally adopt runes in new components while keeping legacy stores for existing code can migrate at their own pace without big-bang rewrites.

Overall, runes represent a significant step forward in clarity and performance for Svelte applications. The explicit nature of $state, $derived, and $effect reduces cognitive load once the initial learning curve is overcome. Teams building dashboards, SaaS tools, or content-heavy sites report faster feature development after migration.

The complete task manager example shown above, along with additional patterns for authentication state, real-time data with WebSockets, and complex form handling, can be found in the accompanying GitHub repository linked at the end of this article. Start by converting one or two components in an existing project to experience the difference firsthand.

Keep reading

Related Articles