Svelte Custom Stores
A custom store wraps a basic store and exposes only the actions you choose. Components call friendly methods such as increment or reset rather than changing raw data. The result is safer code and a clearer design.
The Store Contract
Svelte treats any object with a subscribe method as a store. The method receives a callback, calls it with the current value, and returns a function that cancels the subscription. A custom store satisfies this rule by passing along the subscribe method of an inner writable store.
Building A Counter Store
// counter.js
import { writable } from "svelte/store";
function createCounter() {
const { subscribe, set, update } = writable(0);
return {
subscribe,
increment: () => update((n) => n + 1),
decrement: () => update((n) => n - 1),
reset: () => set(0)
};
}
export const counter = createCounter();The returned object hides set and update. Outside code cannot assign a random value, such as a negative number, unless you offer a method for it.
Using The Counter Store
<script>
import { counter } from "./counter.js";
</script>
<p>Count: {$counter}</p>
<button on:click={counter.decrement}>-</button>
<button on:click={counter.increment}>+</button>
<button on:click={counter.reset}>Reset</button>Custom Store Diagram
Component A ---- counter.increment() ----+
v
Component B ---- counter.reset() ---> [ custom store ]
|
inner writable(0)
|
+--------------+--------------+
v v
Component A shows {$counter} Component B shows {$counter}A Store That Saves To The Browser
A custom store can remember its value between visits through localStorage. The wrapper reads the saved value on creation and writes after each change.
import { writable } from "svelte/store";
export function persistent(key, startValue) {
const hasStorage = typeof localStorage !== "undefined";
const saved = hasStorage ? localStorage.getItem(key) : null;
const store = writable(saved ? JSON.parse(saved) : startValue);
store.subscribe((value) => {
if (hasStorage) localStorage.setItem(key, JSON.stringify(value));
});
return store;
}
export const theme = persistent("theme", "light");The typeof check protects the code when it runs on a server, where localStorage does not exist. Never store passwords or private data in localStorage, since any script on the page can read it.
A Store With Business Rules
Methods can enforce rules. A shopping cart store might refuse a negative quantity or merge duplicate items.
function createCart() {
const { subscribe, update } = writable([]);
return {
subscribe,
add: (name) =>
update((list) => {
const found = list.find((i) => i.name === name);
if (found) return list.map((i) => i.name === name ? { ...i, qty: i.qty + 1 } : i);
return [...list, { name, qty: 1 }];
}),
clear: () => update(() => [])
};
}A Layman Analogy
Picture a bank. Customers do not walk into the vault and rearrange the money. They speak to a teller who offers a short menu: deposit, withdraw, and check balance. The teller enforces the rules and keeps the vault safe. A custom store acts as that teller for your data.
Common Mistakes To Avoid
- Returning set and update directly, which removes the protection
- Forgetting to include subscribe, so the dollar prefix stops working
- Using localStorage without a server check
- Saving sensitive information in browser storage
Key Points
- Any object with a subscribe method qualifies as a store
- Custom stores expose named actions and hide raw setters
- Wrappers can add saving, rules, and logging
- Guard browser-only features when code may run on a server
