Lesson 15 / 25
Stores and When They Still Help
writable, readable, derived and the $store prefix.
The store contract
A store is any object with a subscribe method that calls subscribers with the current value and returns an unsubscribe function. svelte/store provides writable (with set and update), readable (value set from inside, for example a clock) and derived (computed from other stores). In components, prefixing a store name with $ ($count) subscribes automatically and unsubscribes on destroy. With runes, shared state usually belongs in .svelte.ts modules or classes, but stores remain useful for asynchronous streams (websockets, observables), interoperability with libraries that expect the store contract, and existing Svelte 4 code. get(store) reads a value once outside components.
writable, derived and readable
stores.ts plus component usage.
// src/lib/stores.ts
import { writable, derived, readable } from 'svelte/store';
export const theme = writable<'light' | 'dark'>('light');
export const isDark = derived(theme, ($theme) => $theme === 'dark');
export const now = readable(new Date(), (set) => {
const id = setInterval(() => set(new Date()), 1000);
return () => clearInterval(id); // runs when the last subscriber leaves
});
// In a component:
// import { theme, isDark, now } from '$lib/stores';
// <button onclick={() => theme.update((t) => (t === 'light' ? 'dark' : 'light'))}>
// {$isDark ? 'Light mode' : 'Dark mode'}
// </button>
// <time>{$now.toLocaleTimeString()}</time>Do not mix both models needlessly
In new Svelte 5 code, prefer runes for local and shared state; reach for stores when you need the subscribe contract or are integrating existing store-based code.
Quick check: What does $count do inside a component when count is a store?
- Subscribes to the store and unsubscribes automatically on destroy
- Creates a new $state copy that never updates
- Reads the value once at startup only
- Converts the store into a derived rune
Answer
Subscribes to the store and unsubscribes automatically on destroy — The $ prefix is store auto-subscription.