Day 2 of 5
⏱ ~60 minutes
Svelte in 5 Days — Day 2

Svelte Stores

Svelte stores let you share reactive state across components without prop drilling. Writable, readable, and derived stores cover every use case.

Writable Stores

src/lib/stores.js
import { writable, readable, derived } from 'svelte/store';

// writable: can be read and updated by anyone
export const count = writable(0);
export const user = writable(null);
export const cart = writable([]);
Counter.svelte


Count: {$count}

💡
The $storeName syntax auto-subscribes in Svelte components. When the component is destroyed, it unsubscribes automatically. Outside components (in plain .js files), you must call store.subscribe() and manually unsubscribe.

Derived Stores

stores.js — continued
// derived: computed from other stores
export const doubledCount = derived(count, $count => $count * 2);

// derived from multiple stores
export const cartSummary = derived(
  [cart, user],
  ([$cart, $user]) => ({
    total: $cart.reduce((sum, item) => sum + item.price, 0),
    username: $user?.name ?? 'Guest'
  })
);

Custom Stores with Business Logic

cartStore.js
import { writable } from 'svelte/store';

function createCart() {
  const { subscribe, update, set } = writable([]);

  return {
    subscribe,
    addItem(item) {
      update(items => {
        const existing = items.find(i => i.id === item.id);
        if (existing) {
          return items.map(i => i.id === item.id ? {...i, qty: i.qty+1} : i);
        }
        return [...items, { ...item, qty: 1 }];
      });
    },
    removeItem(id) {
      update(items => items.filter(i => i.id !== id));
    },
    clear() { set([]); }
  };
}

export const cart = createCart();
ℹ️
Custom stores expose a subscribe method (making them a store) plus whatever actions you want. Components use $cart to read, and cart.addItem() to write. Clean separation of concerns.
📝 Day 2 Exercise
Build a Global Shopping Cart
  1. Create a cartStore.js with writable state and addItem, removeItem, clear actions.
  2. Create a products page with 6 hardcoded products and an 'Add to Cart' button each.
  3. Create a Cart.svelte component that reads from the store with $cart.
  4. Add a derived store for cart total price. Display it in the Cart component.
  5. Add the Cart component to the layout so it appears on every page.

Day 2 Summary

  • writable(initial) creates a store with set, update, and subscribe methods.
  • $storeName in a Svelte component auto-subscribes and auto-unsubscribes.
  • derived(source, fn) creates a read-only store computed from other stores.
  • Custom stores wrap writable and expose domain-specific methods instead of raw set/update.
Finished this lesson?