Svelte stores let you share reactive state across components without prop drilling. Writable, readable, and derived stores cover every use case.
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([]);
Count: {$count}
$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: 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'
})
);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();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.cartStore.js with writable state and addItem, removeItem, clear actions.products page with 6 hardcoded products and an 'Add to Cart' button each.Cart.svelte component that reads from the store with $cart.derived store for cart total price. Display it in the Cart component.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.writable and expose domain-specific methods instead of raw set/update.