Svelte and SvelteKit 5 cheatsheet

Svelte and SvelteKit 5: Runes (reactivity)

7 common Svelte and SvelteKit 5 tasks.

Component skeleton

A single-file component with state, markup and scoped styles.

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

<button onclick={() => count++}>
  Clicked {count} times
</button>

<style>
  button { font-weight: bold; }
</style>

Reactive state

$state makes a value reactive. Objects and arrays are reactive deeply, so changing a property updates the page.

let todos = $state([{ text: "Learn runes", done: false }]);
todos[0].done = true;
todos.push({ text: "Build an app", done: false });

Derived values

$derived recalculates a value when the state it reads changes.

let count = $state(0);
let doubled = $derived(count * 2);

Side effects

$effect runs after the DOM updates and re-runs when the state it reads changes. Use it for things outside Svelte, not to derive state.

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

Receive props

$props destructures the props a component receives, with defaults.

let { name, greeting = "Hello", onclose }: { name: string; greeting?: string; onclose?: () => void } = $props();

Allow two-way binding of a prop

Mark a prop $bindable so a parent can bind to it with bind:value.

let { value = $bindable("") } = $props();

Share state between components

Put reactive state in a .svelte.ts file and export it. Export an object, because reassigned primitives can't be exported.

// counter.svelte.ts
export const counter = $state({ value: 0 });
export function increment() {
  counter.value++;
}

Was this page helpful?