This concise cheat sheet provides a comprehensive overview of Svelte 5, including component structure, reactivity with runes, props, event handling, bindings, conditional rendering, loops, lifecycle functions, stores, and transitions. Perfect for quick reference and getting started with the latest features of Svelte 5!
A Svelte component consists of <script>
, <style>
, and HTML markup.
<script>
let name = 'World';
</script>
<h1>Hello {name}!</h1>
<style>
h1 {
color: blue;
}
</style>
Svelte 5 introduces runes for managing reactivity.
<script>
let count = $state(0);
</script>
<button on:click={() => count++}>
Count: {count}
</button>
<script>
let count = $state(0);
$effect(() => {
console.log(`Count is ${count}`);
});
</script>
<script>
let count = $state(0);
let doubled = $derived(() => count * 2);
</script>
<p>Doubled: {doubled}</p>
Handle and dispatch events between components.
<script>
function handleClick() {
alert('Button clicked');
}
</script>
<button on:click={handleClick}>
Click me
</button>
<script>
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
function sendMessage() {
dispatch('message', { text: 'Hello!' });
}
</script>
<button on:click={sendMessage}>
Send Message
</button>
Two-way binding between form elements and state.
<script>
let name = $state('');
</script>
<input bind:value={name} placeholder="Enter your name" />
<p>Hello, {name}!</p>
Render content conditionally using {#if}
blocks.
<script>
let isVisible = $state(true);
</script>
<button on:click={() => isVisible = !isVisible}>
Toggle
</button>
{#if isVisible}
<p>The content is visible.</p>
{:else}
<p>The content is hidden.</p>
{/if}
Render lists using {#each
} blocks.
<script>
let items = $state(['Apple', 'Banana', 'Cherry']);
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>
Use lifecycle functions to run code at specific times.
<script>
import { onMount, onDestroy } from 'svelte';
onMount(() => {
console.log('Component mounted');
});
onDestroy(() => {
console.log('Component destroyed');
});
</script>
Manage state across components using stores.
<script>
import { writable } from 'svelte/store';
// Create a writable store
let count = writable(0);
// Update the store
function increment() {
count.update(n => n + 1);
}
</script>
<button on:click={increment}>
Increment
</button>
<!-- Subscribe to the store -->
<p>Count: {$count}</p>
Apply transitions when elements enter or leave the DOM.
<script>
import { fade } from 'svelte/transition';
let visible = $state(true);
</script>
<button on:click={() => visible = !visible}>
Toggle
</button>
{#if visible}
<p transition:fade>
Fading in and out
</p>
{/if}