The cash register at Mrs. Sri's stall has only three buttons for the waiters: "add item", "remove item" and "cancel all". The cash drawer is locked, so nobody can type in just any number. The writable from the Stores lesson is an open drawer: anyone can call set with any value at all.
A custom store is the register with its buttons. A function creates a writable inside it, then only hands out subscribe and the named methods you allow, such as add, remove and clear.
The trouble with a plain writable
In the Stores lesson, cart is a writable that is wide open: anyone can call set and update with any value. That causes two problems:
- Logic spread around. The rule "if the dish is already there, add a portion" is written in MenuList. The rule for removing is written in Header. A new component that needs them writes them again, and may write them differently.
- Any value at all.
cart.set("wrong")is accepted. The store now holds the string"wrong", and$cart.lengthis that string's length, 5. Header showsItems in cart: 5, then{#each}walks each letter, so five rows appear holding nothing butxand a Remove button. Nothing errors right then; the damage only shows up later.
createCart(): wrap the logic
// cart.js
import { writable } from "svelte/store"
function createCart() {
const { subscribe, set, update } = writable([])
return {
subscribe,
add: (name) =>
update((items) => {
const found = items.find((m) => m.name === name)
if (found) return items.map((m) => (m === found ? { ...m, portions: m.portions + 1 } : m))
return [...items, { name, portions: 1 }]
}),
remove: (name) => update((items) => items.filter((m) => m.name !== name)),
clear: () => set([]),
}
}
export const cart = createCart()
const { subscribe, set, update } = writable([])pulls the writable's three methods into plain variables. The writable itself never leaves this function.- The returned object only holds
subscribeand your three methods.setandupdateare used inside, but not handed out. add("Fried Rice")twice gives one row,{ name: "Fried Rice", portions: 2 }, not two rows. That rule now lives in one place.- Wrapping the logic and hiding how it works behind a few methods like this is called encapsulation. It's why a custom store suits complex logic better than a plain writable.
createCart()is called once, and its result is exported. Every component that imports it uses the same cart.
The store contract: subscribe is enough
Why does $cart still work when the object isn't a writable? Because to Svelte, a store is any object with a subscribe method: a method that calls a callback with the value now and on every change, then returns a function that stops. That's called the store contract. A hand-made object counts too:
<script>
const openingTime = {
subscribe(fn) {
fn("07:00")
return () => {}
},
}
</script>
<p>Open at {$openingTime}</p>
The result is Open at 07:00. The other way round, if createCart forgets to return subscribe, {$cart} fails with store.subscribe is not a function (in dev mode, the message says cart is not a store with a subscribe method).
Using it in components
<!-- MenuList.svelte -->
<script>
import { cart } from "./cart.js"
const menu = ["Fried Rice", "Chicken Noodles", "Iced Tea"]
</script>
{#each menu as name}
<button onclick={() => cart.add(name)}>Add {name}</button>
{/each}
<!-- Header.svelte -->
<script>
import { cart } from "./cart.js"
</script>
<p>Items in cart: {$cart.length}</p>
{#each $cart as m}
<p>{m.name} x{m.portions} <button onclick={() => cart.remove(m.name)}>Remove</button></p>
{/each}
<button onclick={cart.clear}>Clear</button>
| Event | Cart holds | Header |
|---|---|---|
| Add Fried Rice | Fried Rice x1 | Items in cart: 1 |
| Add Fried Rice again | Fried Rice x2 | Items in cart: 1 |
| Add Iced Tea | Fried Rice x2, Iced Tea x1 | Items in cart: 2 |
cart.set("wrong") |
(unchanged) | TypeError: cart.set is not a function |
Components only know the method names. If the add rule changes, say to at most 5 portions, you only change cart.js.
Exercise: createCounter
The exercise uses the same pattern for a counter:
<script>
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),
}
}
const counter = createCounter()
</script>
<p>Count: {$counter}</p>
<button onclick={counter.increment}>+</button>
<button onclick={counter.decrement}>-</button>
<button onclick={counter.reset}>Reset</button>
It starts as Count: 0. Click + for Count: 1, click Reset to get back to Count: 0, and from the start, click - for Count: -1. onclick={counter.increment} hands over the method, without parentheses, exactly like the handlers in the Event Handling lesson.
A $state object with methods
In Svelte 5, state and its logic are also often wrapped without a store: an object with methods in a .svelte.js file, its state made with $state. Here is the same cart:
// cart.svelte.js
let items = $state([])
export const cart = {
get items() {
return items
},
add(name) {
const found = items.find((m) => m.name === name)
if (found) {
found.portions += 1
} else {
items.push({ name, portions: 1 })
}
},
clear() {
items = []
},
}
- Like
createCart():itemsis hidden inside that file, and from outside you only see theitemsgetter plus theaddandclearmethods. - Components read it with no
$:{cart.items.length}and{#each cart.items as m}.found.portions += 1updates the view right away, because$stateis reactive all the way down. cart.items = "wrong"fails with aTypeError, becauseitemsonly has a getter, no setter.- You'll also see a class with
$statefields used for the same pattern. Custom stores still work in Svelte 5, and this lesson's exercise uses a custom store.
⚠️ A wrapped store that leaks or breaks
- Without
subscribein the returned object, it's no longer a store, and{$cart}errors.subscribeis required. return storeorreturn { ...store, add }hands outsetandupdatetoo, so anyone can fill it with"wrong"again.onclick={counter.increment()}gives Svelte the result of the call,undefined, not the method. In dev mode, Svelte warns that the handler should be a function. Writeonclick={counter.increment}oronclick={() => counter.increment()}.- The exercise checks for exactly the names
increment,decrementandreset, plussubscribe,writable(andonclickin your code, and needs three buttons reading+,-andReset.
TL;DR: A custom store is a function like createCart() that creates a writable inside, then returns only subscribe plus named methods (add, remove, clear). The logic lives in one place (encapsulation), and nobody can call set from outside: cart.set("wrong") gives a TypeError, while a plain writable accepts it and Header becomes Items in cart: 5. Any object with subscribe is a store (the store contract), so {$cart} keeps working; without subscribe, it errors. writable gives three methods: subscribe, set and update. In Svelte 5, another common form is an object with $state in a .svelte.js file, read with no $. The exercise: createCounter() with increment, decrement and reset, <p>Count: {$counter}</p>, and +, -, Reset buttons that produce Count: 1, Count: -1 and Count: 0.
⚡ The writable stays inside a function
Write:
function createCounter() {
const { subscribe, set, update } = writable(0)
return {
subscribe,
increment: () => update((n) => n + 1),
decrement: () => update((n) => n - 1),
reset: () => set(0),
}
}
Meaning: This function creates a writable inside, then returns only subscribe and named methods. set and update are used inside, but not handed out. The logic lives in one place, and that's called encapsulation.
⚡ set from outside is refused
Guess first: a component runs cart.set("wrong") on the custom cart store. What happens?
TypeError: cart.set is not a function, and the cart doesn't change. A plain writable accepts that value, and Header becomes Items in cart: 5.
Meaning: Components only know the method names, such as cart.add(name), so nobody can put in just any value.
⚡ The store contract: subscribe is enough
Write:
<script>
const openingTime = {
subscribe(fn) {
fn("07:00")
return () => {}
},
}
</script>
<p>Open at {$openingTime}</p>
Meaning: To Svelte, a store is any object with a subscribe method. So {$openingTime} works and shows Open at 07:00. Without subscribe, $ errors.