Svelte 41: Derived Stores
easy⏱ 5 mincoursesvelte
derived(store, fn) — single source
derived takes a source store and a function; every time the source changes, your function re-runs and the derived store's value updates. Like readable, the object you get back only has .subscribe — you can't .set() a derived store, its value is always computed, never assigned.
import { derived } from 'svelte/store';
export const itemCount = derived(cartItems, ($items) =>
$items.reduce((sum, item) => sum + item.qty, 0)
);
derived([a, b], fn) — multiple sources
Pass an ARRAY of source stores instead of one, and your callback receives an array of their current values in the same order. This lets you combine several independent pieces of state — here, itemCount and cartTotal, which are THEMSELVES derived stores — into one formatted summary, without duplicating any state.
export const cartSummary = derived(
[itemCount, cartTotal],
([$itemCount, $cartTotal]) => $itemCount + ' items, $' + $cartTotal.toFixed(2)
);
Derived chains are just as reactive
cartSummary derives from two OTHER derived stores, which each derive from cartItems. Change cartItems once, and the update ripples through the whole chain automatically — Svelte only recomputes what's actually downstream of what changed.