Svelte 42: Custom Stores — The Store Contract
easy⏱ 5 mincoursesvelte
The store contract
writable, readable, derived, and any object YOU build by hand all satisfy the same minimal contract: a .subscribe(callback) method that immediately calls callback with the current value and returns an unsubscribe function. Anything shaped like that can be used with $ syntax, passed to derived, or read with get() — Svelte never checks where it came from.
function createCounter(initial) {
const { subscribe, set, update } = writable(initial);
return {
subscribe,
increment: () => update((n) => n + 1),
decrement: () => update((n) => n - 1),
reset: () => set(initial),
};
}
Hide the primitives, expose intent
Instead of letting every consumer call the generic .set() / .update() on a raw writable — and potentially set it to an invalid value — a custom store returns purpose-built methods that encode the ONLY valid ways the value is allowed to change. set and update never leave the factory function; only subscribe (unmodified) and your curated methods do.
Try it
Click + and - a few times, then Reset. Notice the component never imports writable at all — it only knows about the counter's public methods.