Skip to main content

Web frameworks · Beginner · 20 min

Learn Svelte 5 runes: $state, $derived and $effect

By Padding · Updated 18 Nov 2026
Svelte 5.58.0 · Vite 8.3.8 · Node.js 26 (node:26 image)

You will build a small Svelte 5 app with Vite, a tip calculator and a to-do list that saves itself, using $state, $derived, $effect and $props, snippets and shared state in a .svelte.js module, and you will know how each rune maps to the Svelte 4 code you meet in older projects.

On this page

Svelte is a compiler. You write components in .svelte files, and at build time Svelte turns them into plain JavaScript that updates the exact parts of the page that changed, with no virtual DOM. Svelte 5 replaced the old "assignments are magic" model with runes: a few keywords that start with $ and tell the compiler what is reactive. There are only a handful, and you will use all the common ones in this tutorial.

You build one small app with two parts. A tip calculator shows $state, $derived, event attributes and $props. A to-do list shows deep state, state shared between components from a .svelte.js module, $effect with a cleanup function, and snippets. The last steps show how the same ideas look in Svelte 4, which you will still meet in older code and tutorials, and then build the app for production.

The finished app compiles to a single JavaScript file of something like 40 kB before compression, which matters if your users are on low-end Android phones or prepaid data.

Step 1 · Create the project

Use Vite's project generator with its Svelte template. The --no-interactive flag skips the questions so the command gives the same result every time. Then pin Svelte, Vite and the Svelte plugin to the versions this tutorial uses:

Bash
cd ~
npm create vite@9.3.4 runes-demo -- --template svelte --no-interactive
cd runes-demo
npm install
npm install --save-exact -D svelte@5.58.0 vite@8.3.8 @sveltejs/vite-plugin-svelte@7.3.1

The template is plain JavaScript. Svelte also works with TypeScript (--template svelte-ts), but plain JavaScript keeps the focus on the runes.

Check it worked

List the installed versions:

Bash
npm ls svelte vite
cat src/main.js

npm ls shows svelte@5.58.0 and vite@8.3.8. src/main.js imports mount from svelte and mounts App.svelte into the element with the ID app. mount is the Svelte 5 way to start an app. Svelte 4 code did the same with new App({ target }).

Step 2 · Build a tip calculator with $state and $derived

$state marks a value as reactive: when it changes, Svelte updates every part of the page that uses it. $derived declares a value that is calculated from other reactive values and kept up to date for you.

Create src/lib/TipCalculator.svelte:

Bash
mkdir -p src/lib
cat > src/lib/TipCalculator.svelte <<'SVELTE'
<script>
  let { currency = 'USD', locale = 'en-US' } = $props()

  let bill = $state(0)
  let tipPercent = $state(10)
  let people = $state(1)

  const tip = $derived(((bill ?? 0) * tipPercent) / 100)
  const total = $derived((bill ?? 0) + tip)
  const perPerson = $derived(people >= 1 ? total / people : 0)
  const money = $derived(new Intl.NumberFormat(locale, { style: 'currency', currency }))
</script>

<section class="calculator" aria-label={`Tip calculator in ${currency}`}>
  <label>
    Bill
    <input type="number" min="0" step="any" bind:value={bill} />
  </label>

  <div class="presets" role="group" aria-label="Tip">
    {#each [10, 15, 20] as percent (percent)}
      <button
        type="button"
        aria-pressed={tipPercent === percent}
        onclick={() => (tipPercent = percent)}
      >
        {percent}%
      </button>
    {/each}
  </div>

  <label>
    People
    <input type="number" min="1" step="1" bind:value={people} />
  </label>

  <p>Tip: {money.format(tip)}</p>
  <p>Total: {money.format(total)}</p>
  <p class="share">Each person pays {money.format(perPerson)}</p>
</section>
SVELTE

What each part does:

  • let bill = $state(0) is an ordinary variable that Svelte now watches. You read it and assign to it like any variable. There is no setter function.
  • bind:value={bill} keeps the input and the variable in step both ways. On a type="number" input, Svelte gives you a number, not a string. When the box is empty or holds something that is not a number, the value is null or undefined rather than a number, which is why the sums use bill ?? 0: it covers both.
  • onclick={() => (tipPercent = percent)} is an event attribute. In Svelte 5, events are ordinary attributes named like the DOM property (onclick, oninput, onsubmit), and the handler is a function.
  • tip, total, perPerson and money are derived. Svelte works out which state each one reads, recalculates it only when that state changes, and because they are declared with const, you cannot assign to them. (A derived declared with let can be overridden for a while, which helps with optimistic UI, but this app does not need that.) Chains are fine: total depends on tip, which depends on bill.
  • The $props() line at the top is covered in the next step.

When a derived value needs several lines, use $derived.by with a function, for example const label = $derived.by(() => { ... return text }).

Now replace src/App.svelte and the template's stylesheet so the page shows the calculator:

Bash
cat > src/App.svelte <<'SVELTE'
<script>
  import TipCalculator from './lib/TipCalculator.svelte'
</script>

<main>
  <h1>Runes demo</h1>
  <TipCalculator />
</main>
SVELTE
cat > src/app.css <<'CSS'
body { font-family: system-ui, sans-serif; margin: 0; }
main { max-width: 32rem; margin: 2rem auto; padding: 0 1rem; }
.panel { border: 1px solid #ccc; border-radius: 8px; padding: 1rem; margin-bottom: 1.5rem; }
.calculator { display: grid; gap: 0.5rem; padding: 0.75rem 0; border-top: 1px solid #eee; }
.presets { display: flex; gap: 0.5rem; }
button[aria-pressed='true'] { font-weight: bold; text-decoration: underline; }
.share { font-weight: bold; }
.todos { list-style: none; padding: 0; }
.todos li { display: flex; justify-content: space-between; padding: 0.25rem 0; }
.done { text-decoration: line-through; opacity: 0.6; }
.visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
CSS

Start the dev server in a second terminal, in the ~/runes-demo folder, and leave it running for the rest of the tutorial. Vite updates the page each time you save a file:

Bash
npm run dev

Check it worked

Open http://localhost:5173/. Type 12000 in Bill, click 15% and set People to 4. The page shows Tip: $1,800.00, Total: $13,800.00 and Each person pays $3,450.00, and the 15% button is bold. Every number changes as you type, without any code that says "update the total".

The compiler also catches mistakes, such as assigning to a derived value. Run a production build to ask it:

Bash
npm run build

The build ends with built in and a time, and prints no warnings. If you try total = 5 inside the component and build again, Svelte stops with an error, Cannot assign to constant, because total is declared with const. Remove the line again if you try it.

Step 3 · Pass props with defaults

Props are the inputs a parent component gives a child. In Svelte 5 you read them all with one rune, $props(), and use JavaScript destructuring to pick them out. A default after = applies when the parent does not pass that prop:

Text
let { currency = 'USD', locale = 'en-US' } = $props()

Render two calculators, one with the defaults and one in Nigerian naira:

Bash
cat > src/App.svelte <<'SVELTE'
<script>
  import TipCalculator from './lib/TipCalculator.svelte'
</script>

<main>
  <h1>Runes demo</h1>
  <TipCalculator />
  <TipCalculator currency="NGN" locale="en-NG" />
</main>
SVELTE

Intl.NumberFormat handles the currency symbol and digit grouping for each locale, so the same component works for naira, cedis (GHS), shillings (KES) or rand (ZAR) without changes.

Check it worked

The page now shows two calculators. In the second one, type 5000 in Bill and 2 in People. It shows Each person pays ₦2,750.00, and the first calculator keeps its own numbers. Each component instance has its own $state, so the two never share values. Shared state needs a different approach, which comes next.

Step 4 · Share a to-do list from a .svelte.js module

Runes also work in files that end in .svelte.js (or .svelte.ts). That makes them the place for state that several components use. One rule applies: you cannot export a $state variable that you reassign, because importers would hold the old value. Export an object and change what is inside it instead.

Create src/lib/todos.svelte.js:

Bash
cat > src/lib/todos.svelte.js <<'JS'
export const STORAGE_KEY = 'runes-demo-todos'

const starter = [
  { id: 1, text: 'Read about runes', done: true },
  { id: 2, text: 'Build the tip calculator', done: false },
  { id: 3, text: 'Add a to-do list', done: false },
]

function load() {
  try {
    const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null')
    if (Array.isArray(saved)) return saved
  } catch {
    // No storage, or bad JSON: fall back to the starter list.
  }
  return starter
}

export const todos = $state({ items: load() })

let nextId = Math.max(0, ...todos.items.map((todo) => todo.id)) + 1

export function addTodo(text) {
  todos.items.push({ id: nextId++, text, done: false })
}

export function removeTodo(id) {
  todos.items = todos.items.filter((todo) => todo.id !== id)
}

export function remaining() {
  return todos.items.filter((todo) => !todo.done).length
}
JS

$state on an object or array is deep. Svelte wraps it in a proxy, so todos.items.push(...) and todo.done = true both update the page. You do not have to copy the array each time, as you would in React. Replacing the whole array, as removeTodo does, works too, because items is a property of the exported object and not the exported variable itself. The load function reads a saved list from the browser, which you add in the next step.

Now two components that use the module. TodoList.svelte shows and edits the list, and Summary.svelte shows a count:

Bash
cat > src/lib/TodoList.svelte <<'SVELTE'
<script>
  import { todos, addTodo, removeTodo } from './todos.svelte.js'

  let text = $state('')

  function submit(event) {
    event.preventDefault()
    const trimmed = text.trim()
    if (trimmed === '') return
    addTodo(trimmed)
    text = ''
  }
</script>

<form onsubmit={submit}>
  <input bind:value={text} aria-label="New to-do" placeholder="Add a to-do" />
  <button type="submit">Add</button>
</form>

<ul class="todos">
  {#each todos.items as todo (todo.id)}
    <li>
      <label class:done={todo.done}>
        <input type="checkbox" bind:checked={todo.done} />
        {todo.text}
      </label>
      <button type="button" onclick={() => removeTodo(todo.id)}>
        Remove<span class="visually-hidden"> {todo.text}</span>
      </button>
    </li>
  {/each}
</ul>
SVELTE
cat > src/lib/Summary.svelte <<'SVELTE'
<script>
  import { todos, remaining } from './todos.svelte.js'

  const left = $derived(remaining())
</script>

<p class="summary">{left} of {todos.items.length} to-dos left</p>
SVELTE
cat > src/App.svelte <<'SVELTE'
<script>
  import TipCalculator from './lib/TipCalculator.svelte'
  import TodoList from './lib/TodoList.svelte'
  import Summary from './lib/Summary.svelte'
</script>

<main>
  <h1>Runes demo</h1>
  <TipCalculator />
  <TipCalculator currency="NGN" locale="en-NG" />

  <h2>To-do list</h2>
  <Summary />
  <TodoList />
</main>
SVELTE

Points to notice:

  • onsubmit={submit} receives the normal DOM event. Svelte 5 has no |preventDefault modifier, so the handler calls event.preventDefault() itself.
  • (todo.id) after the each is the key. It lets Svelte keep the right row when items are removed from the middle of the list.
  • bind:checked={todo.done} writes straight into the shared state, and that is allowed because the state is deep.
  • In Summary, $derived(remaining()) tracks everything remaining() reads, even though the reads happen inside a function in another file.

Check it worked

The page shows 2 of 3 to-dos left above the list. Add a to-do called Buy airtime: the count changes to 3 of 4. Tick it: the count goes back to 2 of 4 and the text is struck through. Summary and TodoList are separate components that never pass props to each other, and both stay in step because they read the same state. Reload the page and the list goes back to the three starter items. Saving comes next.

Step 5 · Save the list with $effect and clean up

$effect runs code after the component is on the page, and runs it again whenever any state it read has changed. It is for side effects: talking to something outside Svelte, such as browser storage, a timer, a canvas or a third-party library. If the effect returns a function, Svelte calls that function before the next run and when the component is removed. That is the cleanup.

This component saves the list to localStorage half a second after the last change. Each change cancels the previous timer, so quick edits produce one write instead of many:

Bash
cat > src/lib/AutoSave.svelte <<'SVELTE'
<script>
  import { todos, STORAGE_KEY } from './todos.svelte.js'

  let status = $state('')

  $effect(() => {
    const json = JSON.stringify(todos.items)
    status = 'Saving…'

    const timer = setTimeout(() => {
      try {
        localStorage.setItem(STORAGE_KEY, json)
        status = 'Saved'
      } catch {
        status = 'Could not save on this device'
      }
    }, 500)

    return () => clearTimeout(timer)
  })
</script>

<p class="status" role="status">{status}</p>
SVELTE
cat > src/App.svelte <<'SVELTE'
<script>
  import TipCalculator from './lib/TipCalculator.svelte'
  import TodoList from './lib/TodoList.svelte'
  import Summary from './lib/Summary.svelte'
  import AutoSave from './lib/AutoSave.svelte'
</script>

<main>
  <h1>Runes demo</h1>
  <TipCalculator />
  <TipCalculator currency="NGN" locale="en-NG" />

  <h2>To-do list</h2>
  <Summary />
  <TodoList />
  <AutoSave />
</main>
SVELTE

An effect depends on the state it reads while it runs synchronously. JSON.stringify(todos.items) reads every item and every field, so any edit to the list re-runs the effect. Reads inside the setTimeout callback happen later and are not tracked, which is why the effect takes its snapshot first. The role="status" on the message makes screen readers announce Saved without moving focus.

Saving in the browser also helps people with patchy mobile data: the list survives a reload or a dropped connection, because nothing is sent over the network.

When not to use $effect

Do not use an effect to keep one piece of state in line with another. This works, but it is the wrong tool:

Text
let total = $state(0)
$effect(() => {
  total = bill + tip
})

It renders once with a stale value, runs again, and hides the relationship from the compiler. const total = $derived(bill + tip) says the same thing directly and is always correct. Reach for $effect only when something outside Svelte has to change. For listening to window or document events, Svelte also has <svelte:window onkeydown={...} />, which adds and removes the listener for you.

Check it worked

Below the list, the status reads Saved a moment after the page loads. Add Buy airtime, tick it, and watch the status show Saving… then Saved. Reload the page: Buy airtime is still there and still ticked, and the count still reads 2 of 4 to-dos left. In your browser's developer tools, the Application (or Storage) tab lists a runes-demo-todos key under Local Storage for localhost:5173.

Step 6 · Replace slots with snippets

A component often needs to wrap content that its parent supplies, such as a card or a panel. Svelte 4 used <slot /> for this. Svelte 5 uses snippets: blocks of markup that you pass as props and render with {@render}. Anything you put between a component's tags arrives as a snippet prop called children. Other named snippets are declared with {#snippet name()} inside the tags.

Create src/lib/Panel.svelte, with an optional footer snippet, and wrap both parts of the app in panels:

Bash
cat > src/lib/Panel.svelte <<'SVELTE'
<script>
  let { title = 'Untitled', children, footer } = $props()
</script>

<section class="panel">
  <h2>{title}</h2>
  {@render children()}
  {#if footer}
    <footer>{@render footer()}</footer>
  {/if}
</section>
SVELTE
cat > src/App.svelte <<'SVELTE'
<script>
  import Panel from './lib/Panel.svelte'
  import TipCalculator from './lib/TipCalculator.svelte'
  import TodoList from './lib/TodoList.svelte'
  import Summary from './lib/Summary.svelte'
  import AutoSave from './lib/AutoSave.svelte'
</script>

<main>
  <h1>Runes demo</h1>

  <Panel title="Split the bill">
    <TipCalculator />
    <TipCalculator currency="NGN" locale="en-NG" />
  </Panel>

  <Panel title="To-do list">
    <TodoList />

    {#snippet footer()}
      <Summary />
      <AutoSave />
    {/snippet}
  </Panel>
</main>
SVELTE

Because snippets are ordinary props, Panel can check whether one was passed ({#if footer}) before rendering it. The first panel has no footer, so it renders no empty <footer> element. Snippets can also take arguments, for example {#snippet row(todo)}, which lets a list component ask its parent how to draw each item.

Check it worked

The page shows two bordered panels, Split the bill and To-do list, and the count and save status now sit at the bottom of the second one. Build again to confirm the compiler is happy:

Bash
npm run build

The build ends with built in and lists one CSS file and one JavaScript file under dist/assets/.

Step 7 · Read the Svelte 4 code you will meet

Plenty of Svelte code and answers online predate runes. Svelte 5 still compiles that older syntax in components that use no runes, so a project can contain both. Once a component uses a rune, it is in runes mode: $: and export let are errors there, on: directives and <slot /> still work but give deprecation warnings, and mixing on:click with onclick in one component is an error. Here is a counter in Svelte 4:

Text
<script>
  export let step = 1
  let count = 0
  $: doubled = count * 2
  $: console.log('count is', count)
</script>

<button on:click={() => (count += step)}>{count}, doubled {doubled}</button>
<slot />

And the same in Svelte 5:

Text
<script>
  let { step = 1, children } = $props()
  let count = $state(0)
  const doubled = $derived(count * 2)
  $effect(() => console.log('count is', count))
</script>

<button onclick={() => (count += step)}>{count}, doubled {doubled}</button>
{@render children?.()}

The mapping, line by line:

  • A top-level let was reactive by itself. Now $state says so explicitly, and works in .svelte.js files too.
  • $: x = ... for a computed value becomes $derived. $: with a block of code for a side effect becomes $effect.
  • export let declared a prop. Now one $props() call declares all of them, with defaults.
  • on:click becomes onclick, and modifiers such as |preventDefault move into the handler.
  • <slot /> and named slots become children and named snippets, rendered with {@render}.
  • Stores (writable, $store) still work, but shared state in a .svelte.js module, as in todos.svelte.js, is now the usual choice.

Check it worked

Without looking back, rewrite this Svelte 4 line in your head: $: total = bill + tip. The answer is const total = $derived(bill + tip). Then open src/lib/TipCalculator.svelte and confirm every reactive line uses a rune and none uses $:, export let or on:.

Step 8 · Build and preview the production app

Stop the dev server with Ctrl+C. Build the app and serve the build locally. The preview server keeps running in its terminal, so use a second terminal for the curl command:

Bash
npm run build
Bash
npm run preview
Bash
curl -s http://localhost:4173/ | grep -o '<div id="app"></div>'

Check it worked

npm run build lists dist/index.html, a CSS file and a JavaScript file with their sizes, including the gzip size, which is what a phone downloads. npm run preview prints Local: http://localhost:4173/, and curl prints <div id="app"></div>: the HTML is an empty shell that the JavaScript fills in. Open the address in a browser and repeat the earlier checks: $3,450.00 per person in the first calculator, and a to-do list that survives a reload.

Stop the preview server with Ctrl+C.

The dist/ folder is a set of static files, so any static host or web server can serve it. When you have finished, remove the demo project:

Bash
cd ~
rm -rf ~/runes-demo

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.