Reading Svelte 4 code

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 =…

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>

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>

$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

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} />.

<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>.

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

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.

What you will learn