Svelte Development Skill
This skill provides comprehensive guidance for building modern Svelte applications using reactivity runes (Svelte 5), components, stores, lifecycle hooks, transitions, and animations based on official Svelte documentation.
When to Use This Skill
Use this skill when:
Building high-performance web applications with minimal JavaScript overhead Creating single-page applications (SPAs) with reactive UI Developing interactive user interfaces with compile-time optimization Building embedded widgets and components with small bundle sizes Implementing real-time dashboards and data visualizations Creating progressive web apps (PWAs) with excellent performance Developing component libraries with native reactivity Building server-side rendered applications with SvelteKit Migrating from frameworks with virtual DOM to compiled approach Creating accessible and performant web applications Core Concepts Reactivity with Runes (Svelte 5)
Svelte 5 introduces runes, a new way to declare reactive state with better TypeScript support and clearer semantics.
$state Rune:
$derived Rune:
Count: {count}
Doubled: {doubled}
Quadrupled: {quadrupled}
Active users: {activeCount}
$effect Rune:
$props Rune:
{name}
Age: {age}
{#if onClick} {/if}Components
Components are the building blocks of Svelte applications. Each component is a single file with script, markup, and styles.
Basic Component Structure:
Hello {name}!
Count: {count}
Component Props:
{title}
{description}
Component Events:
<button class="btn {variant}" {disabled} on:click={handleClick}
Slots and Composition:
{#if isOpen}
{/if}
Custom Title
This is custom modal content.
Stores
Stores are observable values that can be shared across components.
Writable Store:
// stores.js import { writable } from 'svelte/store';
export const count = writable(0);
export const user = writable({ name: 'Guest', loggedIn: false });
export const todos = writable([]);
// Custom store with methods function createCounter() { const { subscribe, set, update } = writable(0);
return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0) }; }
export const counter = createCounter();
Using Stores in Components:
Count: {$count}
Welcome, {$user.name}!
{#if !$user.loggedIn}
Counter: {$counter}
Readable Store:
// stores.js import { readable } from 'svelte/store';
export const time = readable(new Date(), (set) => { const interval = setInterval(() => { set(new Date()); }, 1000);
return () => clearInterval(interval); });
export const mousePosition = readable({ x: 0, y: 0 }, (set) => { const handleMouseMove = (e) => { set({ x: e.clientX, y: e.clientY }); };
window.addEventListener('mousemove', handleMouseMove);
return () => { window.removeEventListener('mousemove', handleMouseMove); }; });
Derived Store:
// stores.js import { writable, derived } from 'svelte/store';
export const todos = writable([ { id: 1, text: 'Buy milk', done: false }, { id: 2, text: 'Walk dog', done: true }, { id: 3, text: 'Code review', done: false } ]);
export const completedTodos = derived( todos, $todos => $todos.filter(t => t.done) );
export const activeTodos = derived( todos, $todos => $todos.filter(t => !t.done) );
export const todoStats = derived( todos, $todos => ({ total: $todos.length, completed: $todos.filter(t => t.done).length, active: $todos.filter(t => !t.done).length }) );
// Derived from multiple stores export const firstName = writable('Alice'); export const lastName = writable('Smith');
export const fullName = derived(
[firstName, lastName],
([$firstName, $lastName]) => ${$firstName} ${$lastName}
);
Custom Store with Complex Logic:
// stores/cart.js import { writable, derived } from 'svelte/store';
function createCart() { const { subscribe, set, update } = writable([]);
return { subscribe, addItem: (item) => update(items => { const existing = items.find(i => i.id === item.id); if (existing) { return items.map(i => i.id === item.id ? { ...i, quantity: i.quantity + 1 } : i ); } return [...items, { ...item, quantity: 1 }]; }), removeItem: (id) => update(items => items.filter(i => i.id !== id) ), updateQuantity: (id, quantity) => update(items => items.map(i => i.id === id ? { ...i, quantity } : i) ), clear: () => set([]) }; }
export const cart = createCart();
export const cartTotal = derived( cart, $cart => $cart.reduce((sum, item) => sum + item.price * item.quantity, 0) );
export const cartItemCount = derived( cart, $cart => $cart.reduce((count, item) => count + item.quantity, 0) );
Lifecycle Hooks
Lifecycle hooks let you run code at specific points in a component's lifecycle.
onMount:
{#if loading}
Loading...
{:else if error}
Error: {error}
{:else}
-
{#each data as item}
- {item.name} {/each}
{/if}
onDestroy:
beforeUpdate and afterUpdate:
tick:
Transitions and Animations
Svelte provides built-in transitions and animations for smooth UI effects.
Built-in Transitions:
{#if visible}
{/if}
In and Out Transitions:
{#if visible}
{/if}
Custom Transitions:
{#if visible}
This text will type out character by character
{/if}
Animations:
-
{#each todos as todo (todo.id)}
- {todo.text} {/each}
Deferred Transitions:
Todo
{#each todos.filter(t => !t.done) as todo (todo.id)}Done
{#each todos.filter(t => t.done) as todo (todo.id)}Bindings
Svelte provides powerful two-way binding capabilities.
Input Bindings:
Hello {name}!
Age: {age}
Message length: {message.length}
Selected: {selected}
Checked: {checked}
Apple Banana Orange
Selected: {group.join(', ')}
Component Bindings:
Name: {name}
Element Bindings:
Contenteditable Bindings:
{html}
API Reference Runes (Svelte 5)
$state(initialValue)
Creates reactive state Returns a reactive variable Mutations automatically trigger updates
$derived(expression)
Creates derived reactive value Automatically tracks dependencies Recomputes when dependencies change
$effect(callback)
Runs side effects when dependencies change Can return cleanup function Automatically tracks dependencies
$props()
Declares component props Supports destructuring and defaults Type-safe with TypeScript Store Functions
writable(initialValue, start?)
Creates writable store Returns { subscribe, set, update } Optional start function for setup
readable(initialValue, start)
Creates read-only store Returns { subscribe } Requires start function
derived(stores, callback, initialValue?)
Creates derived store Depends on one or more stores Automatically updates
get(store)
Gets current value without subscription Use sparingly (prefer $store syntax) Lifecycle Functions
onMount(callback)
Runs after component first renders Can return cleanup function Good for data fetching, subscriptions
onDestroy(callback)
Runs before component is destroyed Use for cleanup operations
beforeUpdate(callback)
Runs before DOM updates Access previous state
afterUpdate(callback)
Runs after DOM updates Good for DOM manipulation
tick()
Returns promise that resolves after state changes Ensures DOM is updated Transition Functions
fade(node, params)
Fades element in/out Params: { delay, duration, easing }
fly(node, params)
Flies element in/out Params: { delay, duration, easing, x, y, opacity }
slide(node, params)
Slides element in/out Params: { delay, duration, easing }
scale(node, params)
Scales element in/out Params: { delay, duration, easing, start, opacity }
blur(node, params)
Blurs element in/out Params: { delay, duration, easing, amount, opacity }
crossfade(params)
Creates send/receive transition pair Good for moving elements between lists Animation Functions
flip(node, animation, params)
Animates position changes Use with each blocks Params: { delay, duration, easing } Workflow Patterns Component Composition
Container/Presenter Pattern:
-
{#each todos as todo}
- onToggle(todo.id)} /> {todo.text} {/each}
State Management
Context API Pattern:
Welcome, {$user.name}!
Role: {$user.role}
Form Validation
Form with Validation:
Data Fetching
Fetch with Loading States:
{#if loading}
{:else if error}
Error: {error}
{:else}
-
{#each data as item}
- {item.name} {/each}
{/if}
Best Practices 1. Use Runes for Reactivity (Svelte 5)
Prefer runes over legacy reactive declarations:
- Component Organization
Keep components focused and single-purpose:
- Store Usage
Use stores for shared state, local state for component-specific data:
- Accessibility
Always include proper ARIA attributes and keyboard support:
<button on:click={handleClick} aria-label="Close dialog" aria-pressed={isPressed}
Close
Enter keywords to search
- Performance Optimization
Use keyed each blocks for lists:
{#each items as item (item.id)}
{#each items as item}
- TypeScript Integration
Use TypeScript for type safety:
- CSS Scoping
Leverage Svelte's scoped styles:
- Event Modifiers
Use event modifiers for cleaner code: