Custom Stores — Svelte

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…

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:

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()

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 = []
  },
}

⚠️ A wrapped store that leaks or breaks

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.

What you will learn