Open a Svelte tutorial written before October 2024, or a repo that hasn't moved to Svelte 5, and you'll run into code that looks strange: export let, $:, on:click, <slot />. That's Svelte 4. Svelte 5 still runs it per component, plenty of projects still use it, and one day you'll be the one fixing it. The good news: nearly every old form has a counterpart you've already learned in this track. This lesson is the map from the old to the new.
Picture Mrs. Sri finding her mother's old recipe book. The dishes are the same, fried rice is fried rice, but the amounts are written as "one star-fruit glass" and "a pinch", not grams. Mrs. Sri doesn't need to learn cooking from scratch. She only needs to know how many grams a star-fruit glass is, then she cooks as usual. This lesson is that list of conversions: the Svelte 4 form on the left, its Svelte 5 counterpart on the right.
A plain let and $:
Here is a Svelte 4 counter, close to this lesson's exercise starter:
<script>
let count = 0
$: double = count * 2
</script>
<p class="count">Count: {count}</p>
<p class="double">Double: {double}</p>
<button on:click={() => count += 1}>+1</button>
- A
let count = 0at the top level of<script>is state automatically in Svelte 4. The compiler wraps every assignment to it so the screen follows. Its counterpart islet count = $state(0). $: double = count * 2is a reactive declaration: the$:label makes that line recompute every timecountchanges. Its counterpart islet double = $derived(count * 2). A multi-line block that computes a value,$: { ... }, becomes$derived.by(() => { ... return result }).on:click={...}is the old event directive. Its counterpart is a plain attribute,onclick={...}.
Rewritten with runes:
<script>
let count = $state(0)
let double = $derived(count * 2)
</script>
<p class="count">Count: {count}</p>
<p class="double">Double: {double}</p>
<button onclick={() => count += 1}>+1</button>
Both were tried in the Svelte 5.16 compiler, with the same result: one click turns Count: 0 and Double: 0 into Count: 1 and Double: 2.
push and assignment: the old rule
The Svelte 4 rule that confuses people most: the screen only changes when there's an assignment (the = sign). That's why old code often has a line that looks odd:
<script>
let cart = []
function add() {
cart.push("Iced Tea")
cart = cart
}
</script>
<p>Items in cart: {cart.length}</p>
<button on:click={add}>Add</button>
Take a guess first: if the cart = cart line is removed, what shows after two clicks?
| Click | Svelte 4, push only |
Svelte 4, push then cart = cart |
Svelte 5, push on $state([]) |
|---|---|---|---|
| start | Items in cart: 0 |
Items in cart: 0 |
Items in cart: 0 |
| 1 | Items in cart: 0 |
Items in cart: 1 |
Items in cart: 1 |
| 2 | Items in cart: 0 |
Items in cart: 2 |
Items in cart: 2 |
It stays at Items in cart: 0. push changes the array in memory, but with no assignment Svelte 4 doesn't know. cart = cart is an assignment to itself, only there to ring the bell. Other patterns you'll often see in old code: cart = [...cart, "Iced Tea"] and cart = cart.filter(...). In Svelte 5, $state wraps the array in a proxy that knows every time its contents change, so push alone is enough, and the cart = cart line can go.
One difference you'll feel while debugging: console.log(cart) in Svelte 5 prints a proxy, not a plain array, and dev mode warns: Your `console.log` contained `$state` proxies. Consider using `$inspect(...)` or `$state.snapshot(...)` instead. console.log($state.snapshot(cart)) prints [ 'Iced Tea' ].
$: for side effects, beforeUpdate, afterUpdate
Not every $: fills a variable. Sometimes it just runs something:
<script>
import { afterUpdate } from "svelte"
let count = 0
$: console.log("count changed:", count)
afterUpdate(() => {
console.log("screen updated")
})
</script>
<button on:click={() => count += 1}>+1</button>
- A
$:that runs something (a log, a timer,document.title,localStorage) is a side effect. Its counterpart is$effect(() => { ... }). How to tell them apart:$: name = ...becomes$derived,$: doSomething()becomes$effect. afterUpdatebecomes$effect, andbeforeUpdatebecomes$effect.pre.onMount,onDestroyandtickstay the same.
$effect runs after the DOM updates, and again every time the state it reads changes. The runes version, with a cleanup:
<script>
let count = $state(0)
$effect(() => {
const n = count
console.log("effect ran, count =", n)
return () => console.log("cleanup, previous count =", n)
})
</script>
<button onclick={() => count += 1}>+1</button>
The console, from mounting, one click, then the component being removed:
effect ran, count = 0
cleanup, previous count = 0
effect ran, count = 1
cleanup, previous count = 1
- The returned function is the cleanup: it runs before the next effect and when the component is removed. That's where you stop timers (
clearInterval) and remove listeners, so they don't pile up. const n = countcopies the value first. If the cleanup readcountdirectly, it would get the new value. Tried: the cleanup after the first click prints1, not0.
export let, on:click and createEventDispatcher
The menu card, Svelte 4 version:
<!-- MenuItem.svelte, Svelte 4 -->
<script>
import { createEventDispatcher } from "svelte"
export let name
export let price = 0
const dispatch = createEventDispatcher()
</script>
<p>{name}: ${price}</p>
<button on:click={() => dispatch("order", { name, price })}>Order</button>
Its old parent writes <MenuItem name="Chicken Noodles" price={12} on:order={(e) => (orders = [...orders, e.detail])} />. The Svelte 5 version, plus a component its parent may bind: to:
<!-- MenuItem.svelte -->
<script>
let { name, price = 0, onorder } = $props()
</script>
<p>{name}: ${price}</p>
<button onclick={() => onorder?.({ name, price })}>Order</button>
<!-- PortionInput.svelte -->
<script>
let { value = $bindable(1) } = $props()
</script>
<input type="number" bind:value />
Its parent now writes <MenuItem name="Chicken Noodles" price={12} onorder={(m) => orders.push(m)} /> and <PortionInput bind:value={portions} />.
export let nameandexport let price = 0become one line:let { name, price = 0 } = $props().createEventDispatcheranddispatch("order", data)become a callback prop:onorder?.(data). The old parent read the data fromevent.detail; now the data arrives directly as the argument.- A bare
on:clickon an element means passing the click on to the parent. Its counterpart is takingonclickfrom$props()and writing<button {onclick}>. - Modifiers such as
on:submit|preventDefaultare gone. Writeonsubmit={(e) => { e.preventDefault(); send() }}.|stopPropagationlikewise becomese.stopPropagation()in the handler. $$propsand$$restPropsbecomelet { name, ...rest } = $props().- An
export let valuethe parentbind:s to now needs$bindable. Without that mark, Svelte stops with the errorbind_not_bindable:A component is attempting to bind to a non-bindable property `value`.
<slot> and let:
A card with slots, Svelte 4 version:
<!-- Card.svelte, Svelte 4 -->
<div class="card">
<h3><slot name="title" /></h3>
<slot />
</div>
Its old parent fills the title with <span slot="title">Chicken Noodles</span>. The snippet version:
<!-- Card.svelte -->
<script>
let { title, children } = $props()
</script>
<div class="card">
<h3>{@render title()}</h3>
{@render children()}
</div>
<Card>
{#snippet title()}Chicken Noodles{/snippet}
<p>$12</p>
</Card>
The result is <div class="card"><h3>Chicken Noodles</h3> <p>$12</p></div>.
<slot />becomes{@render children()}, or{@render children?.()}when the parent may send nothing.<slot name="title">in the child, plusslot="title"in the parent, becomes{#snippet title()}in the parent and{@render title()}in the child.<slot item={m}>in the child, pluslet:itemin the parent, becomes{@render row(m)}in the child and{#snippet row(item)}in the parent.$$slots.titlebecomes{#if title}, and a fallback between<slot>and</slot>becomes an{:else}branch.
Map from Svelte 4 to Svelte 5
| Older code (Svelte 4) | What you learned (Svelte 5) |
|---|---|
let count = 0 |
let count = $state(0) |
$: double = count * 2 |
let double = $derived(count * 2) |
$: console.log(count) |
$effect(() => console.log(count)) |
arr.push(x) then arr = arr |
arr.push(x) on $state([]) |
export let name |
let { name } = $props() |
export let value, then bind:value from the parent |
let { value = $bindable() } = $props() |
$$props, $$restProps |
let { name, ...rest } = $props() |
on:click={f} |
onclick={f} |
on:submit with the preventDefault modifier |
onsubmit={(e) => { e.preventDefault(); f() }} |
a bare on:click (forwarding the event) |
let { onclick } = $props() then <button {onclick}> |
createEventDispatcher, on:order, event.detail |
a function prop onorder, its data arriving as the argument |
<slot />, <slot name="title" /> |
{@render children()}, {#snippet title()} and {@render title()} |
<slot item={m}> and let:item |
{@render row(m)} and {#snippet row(item)} |
new App({ target }) |
mount(App, { target }) from svelte |
beforeUpdate, afterUpdate |
$effect.pre, $effect |
<svelte:component this={X} /> |
<X /> |
<svelte:self /> |
the component importing itself |
export let data, export let form (SvelteKit) |
let { data, form } = $props() |
import { page } from "$app/stores" then $page.url.pathname |
import { page } from "$app/state" then page.url.pathname |
writable and $cart |
still working, or $state in a .svelte.js file |
What doesn't change: {#if}, {#each}, {#await}, bind:, class:, use:, transition:, animate:, onMount, setContext and getContext, and <svelte:window> and <svelte:head>. Three of them still work but now have a newer way: class: has the class attribute with an object or array (Svelte 5.16), use: has {@attach} (5.29), and setContext has createContext (5.40).
For a big old repo, there's an official tool:
npx sv migrate svelte-5
It rewrites components into runes using the map above: export let becomes $props(), a $: that fills a variable becomes $derived, on:click becomes onclick, and slots become snippets. What it can't translate exactly gets wrapped in helpers from svelte/legacy: a $: that runs a side effect becomes run(() => { ... }), and a modifier becomes preventDefault(...). createEventDispatcher is left alone, since it still works. So read the result anyway, then swap run for $effect or $derived, and the dispatcher for a callback prop.
Stores and .svelte.js files
Stores from svelte/store aren't deprecated. Svelte 5 still fully supports writable, readable, derived and $cart, in components that use runes too, and many projects and libraries still use them. So when you meet a store in old code, leave it: it isn't a part that has to be migrated.
In new code, shared state can also be written with runes outside a component, in a file ending in .svelte.js. The cart can become shared state without writable():
// src/lib/cart.svelte.js
export const cart = $state([])
export function add(name) {
cart.push({ name, portions: 1 })
}
Any component that imports it and reads cart.length updates too. The .svelte.js ending is required, because only those files go through the Svelte compiler. Exported state can't be reassigned either: export let cart = $state([]) and then cart = [] is refused with Cannot export state from a module if it is reassigned. Change its contents instead, for example cart.length = 0.
Exercise: rewriting a Svelte 4 counter
This exercise's starter is a Svelte 4 counter: let count = 0, $: double = count * 2, and a button with on:click. Rewrite it with runes: let count = $state(0), let double = $derived(count * 2), and onclick. The markup stays. Before any click the page reads Count: 0 and Double: 0. After one click, Count: 1 and Double: 2. What gets checked: $state(, $derived(, onclick=, and no $: or on:click left.
⚠️ What often goes wrong when moving to runes
- Once a component uses a rune,
$:is refused (`$:` is not allowed in runes mode, use `$derived` or `$effect` instead),export letis refused, and mixingon:clickwithonclickis refused (Mixing old (on:click) and new syntaxes for event handling is not allowed). Move one whole component at a time, not half of one. - One
letleft unwrapped. In a runes component, a plainletthat changes isn't reactive any more: the compiler warnsnon_reactive_update, and the screen stays still. Wrap it in$state. - Don't translate a
$:that computes a value into an$effectthat fills other state. Use$derived. An effect that fills other state only runs after the DOM updates, so one change draws twice. - State read inside a cleanup already holds the new value. Copy it into a
constfirst. bind:valueto a prop without$bindableends in the errorbind_not_bindable.
TL;DR: Svelte 4 code is still all over older tutorials and repos, and nearly every form of it has a Svelte 5 counterpart. let count = 0 becomes let count = $state(0), $: double = count * 2 becomes let double = $derived(count * 2), and a side-effect $:, afterUpdate and beforeUpdate become $effect and $effect.pre. push then arr = arr is just push on $state. export let and $$restProps become $props(), a prop the parent binds needs $bindable, on:click becomes onclick, modifiers become e.preventDefault(), createEventDispatcher becomes a callback prop, and <slot> and let: become snippets and {@render}. new App becomes mount, <svelte:component> is just <X />, and $app/stores becomes $app/state. Stores still work, and shared state can also live in a .svelte.js file. npx sv migrate svelte-5 does most of the migration, but its result still needs reading. The exercise: rewrite a Svelte 4 counter with $state, $derived and onclick, from Count: 0, Double: 0 to Count: 1, Double: 2.
⚡ A plain let and $: become runes
Write:
<script>
let count = $state(0)
let double = $derived(count * 2)
</script>
<p class="count">Count: {count}</p>
<p class="double">Double: {double}</p>
<button onclick={() => count += 1}>+1</button>
Meaning: Svelte 4's let count = 0 becomes let count = $state(0), $: double = count * 2 becomes let double = $derived(count * 2), and on:click becomes onclick. One click turns Count: 0 and Double: 0 into Count: 1 and Double: 2.
⚡ The old rule: there has to be an assignment
Write:
<script>
let cart = []
function add() {
cart.push("Iced Tea")
cart = cart
}
</script>
<p>Items in cart: {cart.length}</p>
<button on:click={add}>Add</button>
Guess first: the line cart = cart is removed. What shows after two clicks?
Still Items in cart: 0. push changes the array in memory, but with no assignment Svelte 4 doesn't know.
Meaning: In Svelte 5, $state wraps the array in a proxy, so push on $state([]) is enough and the cart = cart line can go.
⚡ Migrating in one go
Write:
npx sv migrate svelte-5
Meaning: This official tool rewrites components into runes: export let becomes $props(), a $: that fills a variable becomes $derived, on:click becomes onclick, and slots become snippets. Its result still needs reading, because what it can't translate exactly gets wrapped in helpers from svelte/legacy.