Svelte
Svelte 5 cheat sheet covering runes, snippets, reactivity, components, stores, and SvelteKit integration with practical code examples.
Other Svelte Sheets
Setup & Basics
Getting started with Svelte 5 and core concepts
Setting up a new Svelte 5 project
# Quick Start
npm create vite@latest my-app -- --template svelte
cd my-app && npm install && npm run devBasic Svelte component anatomy
<!-- MyComponent.svelte -->
<script>
let message = 'Hello Svelte';
</script>
<h1>{message}</h1>
<style>
h1 { color: #ff3e00; }
</style>Runes (Svelte 5)
New reactive primitives in Svelte 5
Reactive state management rune
<script>
// Simple state
let count = $state(0);
// Object state
let user = $state({ name: 'Alice', age: 25 });
// Array state
let todos = $state([]);
</script>
<button onclick={() => count++}>
Count: {count}
</button>Computed values from state
<script>
let count = $state(0);
// Simple derived
const doubled = $derived(count * 2);
// Object derived
const stats = $derived({
count,
doubled: count * 2,
isEven: count % 2 === 0
});
</script>
<p>Count: {count}, Doubled: {doubled}</p>Side effects and lifecycle
<script>
import { untrack } from 'svelte';
let count = $state(0);
// Simple effect
$effect(() => {
console.log('Count:', count);
});
// Effect with cleanup
$effect(() => {
const timer = setInterval(() => {
console.log('Tick');
}, 1000);
return () => clearInterval(timer);
});
</script>Opt out of deep reactivity, derive with a function, debug reactive values
<script>
// $state.raw — skip deep proxy wrapping (huge perf win for big arrays/objects)
let rows = $state.raw([])
// Must replace the whole reference; mutating in place won't trigger updates:
rows = [...rows, newRow] // ✓
// rows.push(newRow) // ✗ — no reactivity
// $derived.by — function form for multi-statement derivations
let stats = $derived.by(() => {
const total = rows.length
const active = rows.filter(r => r.active).length
return { total, active, ratio: total ? active / total : 0 }
})
// $inspect — log a reactive value (dev-only)
$inspect(rows)
$inspect(stats).with((type, value) => {
if (type === 'update') console.log('stats changed', value)
})
</script>Control Flow
Conditional rendering and loops
Conditional rendering
{#if loggedIn}
<p>Welcome back!</p>
{:else}
<p>Please log in</p>
{/if}
{#if score >= 90}
<p>A</p>
{:else if score >= 80}
<p>B</p>
{:else}
<p>F</p>
{/if}Rendering lists and arrays
{#each items as item}
<li>{item.name}</li>
{/each}
{#each items as item, index}
<li>{index + 1}. {item.name}</li>
{/each}
{#each items as item (item.id)}
<li>{item.name}</li>
{/each}Stores
Global state management
Creating and using writable stores
// stores.js
import { writable } from 'svelte/store';
export const count = writable(0);
export const user = writable({ name: 'Guest' });
// Component.svelte
<script>
import { count } from './stores.js';
</script>
<button onclick={() => $count++}>
Count: {$count}
</button>Computed and read-only stores
// stores.js
import { readable, derived } from 'svelte/store';
// Readable store
export const time = readable(new Date(), (set) => {
const interval = setInterval(() => {
set(new Date());
}, 1000);
return () => clearInterval(interval);
});
// Derived store
export const doubled = derived(count, $count => $count * 2);SvelteKit
Full-stack framework for Svelte
File-based routing in SvelteKit
// File structure
src/routes/
+page.svelte // index (/)
+layout.svelte // root layout
about/
+page.svelte // /about
blog/
[slug]/
+page.svelte // /blog/:slugProps & Bindings
Component props and data binding
Component props in Svelte 5
<script>
// Basic props
let { name, age } = $props();
// With defaults
let {
title = 'Default',
count = 0
} = $props();
</script>
<h1>{title}</h1>
<p>{name} is {age}</p>Two-way binding for props
<!-- Child.svelte -->
<script>
let { value = $bindable() } = $props();
</script>
<input bind:value />
<!-- Parent.svelte -->
<script>
import Child from './Child.svelte';
let text = $state('');
</script>
<Child bind:value={text} />
<p>Parent sees: {text}</p>Two-way data binding with form elements
<script>
let text = $state('');
let checked = $state(false);
let selected = $state('opt1');
let files = $state();
</script>
<input bind:value={text} />
<input type="checkbox" bind:checked />
<select bind:value={selected}>
<option value="opt1">Option 1</option>
<option value="opt2">Option 2</option>
</select>
<input type="file" bind:files />Snippets (Svelte 5)
Reusable template fragments (replaces slots)
Creating and using snippets
{#snippet greeting(name)}
<p>Hello, {name}!</p>
{/snippet}
{@render greeting('World')}
{@render greeting('Svelte')}Passing snippets between components
<!-- Card.svelte -->
<script>
let { header, children, footer } = $props();
</script>
<div class="card">
{@render header?.()}
{@render children()}
{@render footer?.()}
</div>
<!-- Usage -->
<Card>
{#snippet header()}
<h2>Title</h2>
{/snippet}
{#snippet children()}
<p>Content</p>
{/snippet}
</Card>Events & Actions
Event handling and element actions
Handling DOM events in Svelte 5
<script>
let count = $state(0);
function handleClick() {
count++;
}
</script>
<button onclick={handleClick}>
Count: {count}
</button>
<button onclick={() => count++}>
Increment
</button>Reusable element behaviors
<script>
function tooltip(node, text) {
// Setup
// Return { update, destroy }
}
</script>
<button use:tooltip={'Hover me'}>
Button
</button>Transitions & Animations
Built-in transitions and animations
Svelte built-in transition functions
<script>
import { fade, fly, slide } from 'svelte/transition';
let visible = $state(true);
</script>
{#if visible}
<div transition:fade>
Fades in and out
</div>
<div transition:fly={{ x: 200 }}>
Flies in from right
</div>
<div transition:slide>
Slides down
</div>
{/if}Creating custom transition functions
<script>
function typewriter(node, { speed = 1 }) {
const text = node.textContent;
const duration = text.length / (speed * 0.01);
return {
duration,
tick: t => {
const i = Math.trunc(text.length * t);
node.textContent = text.slice(0, i);
}
};
}
</script>
{#if visible}
<p transition:typewriter>
Hello World!
</p>
{/if}Special Elements
Svelte special elements and components
Svelte special elements for advanced use cases
<!-- Bind to window -->
<svelte:window
onresize={handleResize}
onscroll={handleScroll}
/>
<!-- Dynamic component -->
<svelte:component this={ComponentName} />
<!-- Bind to body -->
<svelte:body onclick={handleClick} />
<!-- Insert into head -->
<svelte:head>
<title>Page Title</title>
</svelte:head>