Svelte Stores
The writable/readable store contract that predates runes, and where it still pulls its weight today.
阅读需 2 分钟
Before runes existed, Svelte's answer to shared, reactive state was the store — a small object with a subscribe method, from the svelte/store module. Runes now cover most of the same ground (as you saw in the previous lesson), but stores are still common in existing codebases and libraries, and worth recognizing.
Writable stores
// count.js
import { writable } from 'svelte/store';
export const count = writable(0);<script>
import { count } from './count.js';
</script>
<p>Count: {$count}</p>
<button onclick={() => count.update((n) => n + 1)}>Increment</button>
<button onclick={() => count.set(0)}>Reset</button>writable(0) creates a store holding 0, with .set(value) to replace it and .update(fn) to derive the next value from the current one. Inside a component, prefixing a store's variable name with $ — $count — automatically subscribes to it and unwraps its current value; Svelte generates the subscription and cleanup for you at compile time.
Derived and readable stores
import { writable, derived } from 'svelte/store';
export const count = writable(0);
export const doubled = derived(count, ($count) => $count * 2);derived builds a new store from one or more existing ones, recalculating whenever a source store changes — the store-based counterpart to the $derived rune. readable is similar to writable but doesn't expose .set/.update to consumers, useful for values (like a WebSocket connection's status) that only the store's own internal logic should change.
How this compares to runes-based shared state
Both solve the same problem — reactive state usable outside any single component — but with different mechanics:
- A store is a plain object following the
subscribecontract; you can build your own from scratch, and any store-compatible library works the same way. The$storeprefix syntax only auto-subscribes inside.sveltefiles, though — a plain.jsfile has to call.subscribe()manually. - Runes-based shared state (the previous lesson) uses
$stateinside a.svelte.jsmodule, works identically inside or outside components, and doesn't need a separate subscribe/unsubscribe mechanism at all.
Which to reach for
For new Svelte 5 code, runes-based shared state is generally the more direct option — one reactivity model throughout your whole app, rather than two. Stores remain the right choice when you're integrating with an existing library built around the store contract, or maintaining a codebase that already uses them extensively. Recognizing both is what matters here — you'll run into stores in the wild well before runes-based sharing fully displaces them.