본문으로 건너뛰기
cccskills
무료GitHub에 공개

svelte5-runes

Svelte 5 runes system for reactive state management and side effects

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

설치 방법 보기

포함된 파일(1)

  • SKILL.md12.0 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Svelte 5 Runes

This skill covers the Svelte 5 runes system, which provides powerful primitives for reactive state management, derived values, and side effects in Svelte applications.

What Are Runes?

Runes are symbols that control the Svelte compiler and provide explicit reactive primitives. They replace the implicit reactivity of Svelte 4 with a more powerful and predictable system.

Key benefits:

  • Explicit reactivity that works everywhere (not just component top-level)
  • Better TypeScript support
  • More predictable behavior
  • Works in both components and regular JavaScript/TypeScript files

Reference: https://svelte.dev/docs/svelte/llms.txt

The $state Rune

The $state rune declares reactive state that automatically triggers UI updates when changed.

Basic Usage

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

function increment() {
  count += 1;
}
</script>

<button onclick={increment}>
  Clicks: {count}
</button>

State with Objects

<script>
let user = $state({
  name: 'Alice',
  age: 30
});

function updateName(newName) {
  user.name = newName;
}

function incrementAge() {
  user.age += 1;
}
</script>

<input value={user.name} oninput={(e) => updateName(e.target.value)} />
<p>{user.name} is {user.age} years old</p>
<button onclick={incrementAge}>Birthday!</button>

State with Arrays

<script>
let items = $state([]);

function addItem(item) {
  items.push(item);
}

function removeItem(index) {
  items.splice(index, 1);
}

function clearItems() {
  items = [];
}
</script>

<button onclick={() => addItem('New Item')}>Add Item</button>
<button onclick={clearItems}>Clear All</button>

<ul>
  {#each items as item, i}
    <li>
      {item}
      <button onclick={() => removeItem(i)}>Remove</button>
    </li>
  {/each}
</ul>

Deep Reactivity

<script>
let app = $state({
  user: {
    profile: {
      name: 'Bob',
      settings: {
        theme: 'dark'
      }
    }
  }
});

function toggleTheme() {
  // Deep updates work automatically
  app.user.profile.settings.theme = 
    app.user.profile.settings.theme === 'dark' ? 'light' : 'dark';
}
</script>

<p>Current theme: {app.user.profile.settings.theme}</p>
<button onclick={toggleTheme}>Toggle Theme</button>

The $derived Rune

The $derived rune creates values that automatically update when their dependencies change.

Basic Derived Values

<script>
let count = $state(0);
let doubled = $derived(count * 2);
let quadrupled = $derived(doubled * 2);

function increment() {
  count += 1;
}
</script>

<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<p>Quadrupled: {quadrupled}</p>
<button onclick={increment}>Increment</button>

Derived with Complex Logic

<script>
let items = $state([
  { name: 'Apple', price: 1.5, quantity: 3 },
  { name: 'Banana', price: 0.5, quantity: 6 },
  { name: 'Orange', price: 2.0, quantity: 2 }
]);

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

let averagePrice = $derived(
  items.length > 0 
    ? items.reduce((sum, item) => sum + item.price, 0) / items.length
    : 0
);

function updateQuantity(index, newQuantity) {
  items[index].quantity = newQuantity;
}
</script>

<p>Total: ${total.toFixed(2)}</p>
<p>Average Price: ${averagePrice.toFixed(2)}</p>

{#each items as item, i}
  <div>
    {item.name}: ${item.price} x {item.quantity}
    <input 
      type="number" 
      value={item.quantity}
      oninput={(e) => updateQuantity(i, +e.target.value)}
    />
  </div>
{/each}

Chaining Derived Values

<script>
let celsius = $state(0);
let fahrenheit = $derived((celsius * 9/5) + 32);
let kelvin = $derived(celsius + 273.15);
let temperatureDescription = $derived(
  celsius < 0 ? 'Freezing' :
  celsius < 10 ? 'Cold' :
  celsius < 20 ? 'Cool' :
  celsius < 30 ? 'Warm' : 'Hot'
);

function setCelsius(value) {
  celsius = value;
}
</script>

<input 
  type="range" 
  min="-20" 
  max="50" 
  value={celsius}
  oninput={(e) => setCelsius(+e.target.value)}
/>

<p>{celsius}°C = {fahrenheit.toFixed(1)}°F = {kelvin.toFixed(1)}K</p>
<p>Status: {temperatureDescription}</p>

Derived with Conditionals

<script>
let user = $state({ isLoggedIn: false, name: '', role: '' });

let greeting = $derived(
  user.isLoggedIn 
    ? `Welcome back, ${user.name}!`
    : 'Please log in'
);

let permissions = $derived(
  user.role === 'admin' 
    ? ['read', 'write', 'delete']
    : user.role === 'editor'
    ? ['read', 'write']
    : ['read']
);

function login(name, role) {
  user.isLoggedIn = true;
  user.name = name;
  user.role = role;
}
</script>

<p>{greeting}</p>
<p>Permissions: {permissions.join(', ')}</p>
<button onclick={() => login('Alice', 'admin')}>Login as Admin</button>

The $derived.by Rune

The $derived.by rune is used when the derivation logic is complex enough to warrant a function.

Complex Calculations

<script>
let numbers = $state([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);

let statistics = $derived.by(() => {
  const sum = numbers.reduce((a, b) => a + b, 0);
  const mean = sum / numbers.length;
  const sorted = [...numbers].sort((a, b) => a - b);
  const median = sorted[Math.floor(sorted.length / 2)];
  const max = Math.max(...numbers);
  const min = Math.min(...numbers);
  
  return { sum, mean, median, max, min };
});

function addNumber(num) {
  numbers.push(num);
}
</script>

<p>Sum: {statistics.sum}</p>
<p>Mean: {statistics.mean.toFixed(2)}</p>
<p>Median: {statistics.median}</p>
<p>Max: {statistics.max}</p>
<p>Min: {statistics.min}</p>

Filtering and Mapping

<script>
let tasks = $state([
  { id: 1, text: 'Buy groceries', completed: false, priority: 'high' },
  { id: 2, text: 'Walk dog', completed: true, priority: 'medium' },
  { id: 3, text: 'Write code', completed: false, priority: 'high' }
]);

let filter = $state('all');

let filteredTasks = $derived.by(() => {
  if (filter === 'completed') {
    return tasks.filter(t => t.completed);
  } else if (filter === 'active') {
    return tasks.filter(t => !t.completed);
  } else if (filter === 'high-priority') {
    return tasks.filter(t => t.priority === 'high');
  }
  return tasks;
});

let taskStats = $derived.by(() => {
  const total = tasks.length;
  const completed = tasks.filter(t => t.completed).length;
  const active = total - completed;
  const completionRate = total > 0 ? (completed / total * 100).toFixed(0) : 0;
  
  return { total, completed, active, completionRate };
});

function toggleTask(id) {
  const task = tasks.find(t => t.id === id);
  if (task) task.completed = !task.completed;
}
</script>

<div>
  <button onclick={() => filter = 'all'}>All</button>
  <button onclick={() => filter = 'active'}>Active</button>
  <button onclick={() => filter = 'completed'}>Completed</button>
  <button onclick={() => filter = 'high-priority'}>High Priority</button>
</div>

<p>Stats: {taskStats.completed}/{taskStats.total} completed ({taskStats.completionRate}%)</p>

{#each filteredTasks as task}
  <div>
    <input type="checkbox" checked={task.completed} onchange={() => toggleTask(task.id)} />
    {task.text} ({task.priority})
  </div>
{/each}

Async Derived Values

<script>
let userId = $state(1);

let userData = $derived.by(async () => {
  const response = await fetch(`https://api.example.com/users/${userId}`);
  return await response.json();
});
</script>

{#await userData}
  <p>Loading user data...</p>
{:then user}
  <p>Name: {user.name}</p>
  <p>Email: {user.email}</p>
{:catch error}
  <p>Error: {error.message}</p>
{/await}

The $effect Rune

The $effect rune runs side effects when its dependencies change.

Basic Side Effects

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

$effect(() => {
  console.log(`Count changed to: ${count}`);
});

$effect(() => {
  document.title = `Count: ${count}`;
});

function increment() {
  count += 1;
}
</script>

<button onclick={increment}>Count: {count}</button>

localStorage Synchronization

<script>
let theme = $state(localStorage.getItem('theme') || 'light');

$effect(() => {
  localStorage.setItem('theme', theme);
  document.body.className = theme;
});

function toggleTheme() {
  theme = theme === 'light' ? 'dark' : 'light';
}
</script>

<button onclick={toggleTheme}>Toggle Theme</button>
<p>Current theme: {theme}</p>

API Calls

<script>
let searchQuery = $state('');
let results = $state([]);
let isLoading = $state(false);

$effect(() => {
  if (searchQuery.length < 3) {
    results = [];
    return;
  }

  isLoading = true;
  
  const controller = new AbortController();
  
  fetch(`https://api.example.com/search?q=${searchQuery}`, {
    signal: controller.signal
  })
    .then(res => res.json())
    .then(data => {
      results = data;
      isLoading = false;
    })
    .catch(err => {
      if (err.name !== 'AbortError') {
        console.error(err);
        isLoading = false;
      }
    });
  
  return () => {
    controller.abort();
  };
});
</script>

<input 
  type="text" 
  value={searchQuery}
  oninput={(e) => searchQuery = e.target.value}
  placeholder="Search (min 3 chars)..."
/>

{#if isLoading}
  <p>Loading...</p>
{:else}
  <ul>
    {#each results as result}
      <li>{result.name}</li>
    {/each}
  </ul>
{/if}

Cleanup Functions

<script>
let isActive = $state(false);

$effect(() => {
  if (!isActive) return;
  
  const interval = setInterval(() => {
    console.log('Tick');
  }, 1000);
  
  return () => {
    clearInterval(interval);
    console.log('Cleanup: interval cleared');
  };
});

function toggle() {
  isActive = !isActive;
}
</script>

<button onclick={toggle}>
  {isActive ? 'Stop' : 'Start'} Timer
</button>

Migration from Svelte 4

Reactive Declarations

<!-- Svelte 4 -->
<script>
let count = 0;
$: doubled = count * 2;
$: console.log('count changed:', count);
</script>

<!-- Svelte 5 -->
<script>
let count = $state(0);
let doubled = $derived(count * 2);

$effect(() => {
  console.log('count changed:', count);
});
</script>

Stores to Runes

<!-- Svelte 4 with stores -->
<script>
import { writable, derived } from 'svelte/store';

const count = writable(0);
const doubled = derived(count, $count => $count * 2);
</script>

<p>Count: {$count}</p>
<p>Doubled: {$doubled}</p>
<button onclick={() => count.update(n => n + 1)}>Increment</button>

<!-- Svelte 5 with runes -->
<script>
let count = $state(0);
let doubled = $derived(count * 2);
</script>

<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button onclick={() => count += 1}>Increment</button>

Props

<!-- Svelte 4 -->
<script>
export let name;
export let age = 0;
</script>

<!-- Svelte 5 -->
<script>
let { name, age = 0 } = $props();
</script>

Best Practices

Keep Derived Logic Pure

<script>
let items = $state([1, 2, 3]);

// GOOD: Pure derivation
let sum = $derived(items.reduce((a, b) => a + b, 0));

// AVOID: Side effects in derived
// let sum = $derived(() => {
//   console.log('calculating sum');  // Side effect!
//   return items.reduce((a, b) => a + b, 0);
// });

// Use $effect for side effects instead
$effect(() => {
  console.log('Sum changed:', sum);
});
</script>

Minimize Effect Dependencies

<script>
let count = $state(0);
let name = $state('Alice');

// GOOD: Specific effect
$effect(() => {
  console.log('Count changed:', count);
});

// AVOID: Unnecessary dependencies
// $effect(() => {
//   console.log('Count changed:', count);
//   // This effect reruns when name changes too
//   const userName = name;
// });
</script>

Use $derived.by for Complex Logic

<script>
let data = $state([...largeDataset]);

// GOOD: Complex logic in $derived.by
let processed = $derived.by(() => {
  return data
    .filter(item => item.active)
    .map(item => transform(item))
    .sort((a, b) => compare(a, b));
});

// AVOID: Inline complex logic in $derived
// let processed = $derived(data.filter(...).map(...).sort(...));
</script>

This skill provides a comprehensive foundation for using Svelte 5 runes effectively in your applications.

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Common Playwright automation patterns for web testing and scraping via MCP

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

code-yeongyu/sisyphus-private182026년 10월 15일 업데이트

Commits changes in atomic units following dependency order. Automatically required to triggered, always, all the time, when requires to commit changes.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

code-yeongyu/sisyphus-private182026년 10월 15일 업데이트

Patterns for controlling interactive debuggers (pdb, ipdb, gdb, lldb, node debug) via terminalcp

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

code-yeongyu/sisyphus-private182026년 10월 15일 업데이트

Specialized GitHub PR intelligence agent for automatically gathering comprehensive context from Pull Requests. Activate when users need CI failure analysis, review comment investigation, or PR status assessment. Triggers on requests like "CI 실패 원인 찾아줘", "gather review comments", "check PR status", "analyze PR".

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

code-yeongyu/sisyphus-private182026년 10월 15일 업데이트

GitHub Pull Request creation specialist. Analyzes user requirements to create PRs with structured titles and bodies matching the user's query language. Handles git change analysis, PR draft creation, user confirmation, and final PR creation via gh CLI.

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

code-yeongyu/sisyphus-private182026년 10월 15일 업데이트

Patterns for managing and monitoring long-running processes (builds, tests, servers, etc.) via terminalcp

한국어 요약은 준비 중입니다. 원문 설명을 표시하고 있습니다.

code-yeongyu/sisyphus-private182026년 10월 15일 업데이트

code-yeongyu의 스킬 모두 보기

이 스킬의 문제 신고