Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 35 ยท State Beyond One Component

Svelte Stores

Learn svelte/store in Svelte 5: writable, readable and derived stores, the $store auto-subscription syntax, custom stores, and when runes are enough.

Before runes, stores were Svelte's way to share state. They are still part of Svelte 5, and you will meet them in existing code, libraries and SvelteKit ($page-style values from $app/stores, the $app/state module being the newer rune-based replacement). Knowing how they work lets you read and maintain that code, and use them where they are still a good fit: streams of values over time.

The store contract

A store is any object with a subscribe method that:

  1. takes a callback and calls it immediately with the current value,
  2. calls it again whenever the value changes,
  3. returns an unsubscribe function.

That is all. Svelte gives you ready-made stores in svelte/store.

writable

JavaScript
import { writable } from 'svelte/store';

export const count = writable(0);

count.set(5);
count.update((n) => n + 1);

set replaces the value; update computes a new one from the old. Anyone subscribed is notified, but only if the value changed (for objects, the comparison is by reference, so a new object always notifies).

The $ prefix

In a component, prefix a store's name with $ to read it and subscribe automatically. Svelte unsubscribes when the component is destroyed:

SVELTE
<script>
  import { count } from './stores.js';
</script>

<button onclick={() => count.update((n) => n + 1)}>
  Clicked {$count} times
</button>

<button onclick={() => ($count = 0)}>Reset</button>

$count = 0 is shorthand for count.set(0). This works for writable stores only. The $ prefix is allowed at the top level of a component script and in markup, but not in plain .js modules, where you call subscribe or get yourself.

Do not mix this up with runes: $count (a store value) and $state (a rune) both start with a dollar sign, but a store is imported by you and a rune is compiler syntax. Names beginning with $ are reserved, so avoid naming your own variables that way.

readable

A store that only the module can change, useful for values that come from outside, like the time or the window size:

JavaScript
import { readable } from 'svelte/store';

export const time = readable(new Date(), (set) => {
  const id = setInterval(() => set(new Date()), 1000);
  return () => clearInterval(id); // runs when the last subscriber leaves
});

The second argument is a start function that runs when the first subscriber arrives and returns a cleanup that runs when the last one leaves. So the timer only runs while someone is watching.

derived

derived builds a store from other stores:

JavaScript
import { derived, writable } from 'svelte/store';

export const price = writable(10);
export const qty = writable(3);

export const total = derived([price, qty], ([$price, $qty]) => $price * $qty);

With a single source you can pass the store directly: derived(price, ($p) => $p * 2). For async derivation, give the callback a set parameter: derived(query, ($q, set) => { fetchResults($q).then(set); }, []).

get and custom stores

get(store) reads the current value once, without subscribing (it subscribes and unsubscribes immediately):

JavaScript
import { get } from 'svelte/store';
console.log(get(count));

A custom store wraps a writable and exposes only the actions you want:

JavaScript
import { writable } from 'svelte/store';

function createCounter() {
  const { subscribe, set, update } = writable(0);
  return {
    subscribe,
    increment: () => update((n) => n + 1),
    reset: () => set(0)
  };
}

export const counter = createCounter();

Components use $counter and counter.increment(). Because it has subscribe, it follows the contract and works with $.

Store family

writable set and update
readable Changed from inside only
derived Built from other stores
custom Your own actions
1 / 2

Stores or runes?

For most new code, runes in .svelte.js modules are simpler: no subscribe, no $, no .set(). Reach for stores when:

  • you work with an existing codebase or library that uses them,
  • you need a stream of values over time with start/stop behavior (the readable start function is neat for this),
  • you use RxJS-style libraries: anything with subscribe is accepted by $.

Runes cover state, derived values and effects without the extra concepts. See shared state in modules for the rune way.

Stand-in: implementing writable and derived

This stand-in re-creates the store contract in about twenty lines. It is close to how the real writable works, but without the safety features. Seeing it makes the $store syntax feel less magical.

JS writable, derived and subscribe (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS A readable clock that stops when unobserved (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What must an object have to be a Svelte store?

    The subscribe contract is all that is required.
  2. 2. What does $count = 0 do when count is a writable store?

    Assigning to $store sets the value of a writable store.
  3. 3. When does the start function of a readable store run?

    It starts on the first subscription and its cleanup runs when the last subscriber leaves.
  4. 4. Which tool is generally simpler for new shared state in Svelte 5?

    Runes avoid subscribe, set and the $ prefix, though stores still fit streams over time.

Summary

  • A store is any object with subscribe; writable, readable, derived and get live in svelte/store.
  • $store auto-subscribes in components, and $store = value sets a writable store.
  • readable start functions run only while someone listens.
  • Custom stores expose chosen actions while keeping subscribe.
  • For new code, prefer runes in .svelte.js modules; use stores for streams and legacy code.

Next: Back to the Svelte course