let total = $derived(...) from the Reactive Declarations lesson only lives inside one component. But the order total is needed in many places: the header, the cashier screen and the payment page. That's what a derived store is for: a store whose value is computed from other stores, and recomputed by itself whenever its sources change. The formula is the same as in $derived, but a derived store lives in stores.js and many components can use it.
Picture the cashier screen at Mrs. Sri's stall, connected to the cart. Every time a waiter adds an order, the total on the screen changes by itself. The cashier can't type the total by hand. To change that number, the cart itself has to change. In code, the cashier screen is the derived store total, and the cart is its source store.
derived: a store from other stores
This is stores.js from the Svelte Stores lesson, with a total store added. This time each item in the cart is an object with a name and a price, for example { name: "Fried Rice", price: 15 }:
// stores.js
import { writable, derived } from "svelte/store"
export const cart = writable([])
export const total = derived(cart, ($cart) =>
$cart.reduce((sum, m) => sum + m.price, 0)
)
derived(source, formula)creates a new store.derivedis imported from"svelte/store", just likewritable.formulais a function that receives the source's value. The parameter can have any name. By habit it gets a$in front, such as$cart, as a reminder that it's the store's value, not the store.- What
formulareturns becomes the value oftotal. Here,reduceadds up the price of every item in the cart, starting from 0.
Reading a derived store
A derived store is read exactly like any other store, with $:
<!-- Cashier.svelte -->
<script>
import { total } from "./stores.js"
</script>
<p>Total: ${$total.toFixed(2)}</p>
| Event | cart holds |
total |
Cashier |
|---|---|---|---|
| Start | [] |
0 | Total: $0.00 |
| Add Fried Rice | 1 item, 15 | 15 | Total: $15.00 |
| Add Iced Tea | 2 items, 15 + 5 | 20 | Total: $20.00 |
Not a single line writes to total. The Add button only calls cart.update(...), then the formula reruns by itself.
From several stores at once
The source can be an array. The formula then receives an array holding the value of each store, in the same order. Here the toPay store is computed from total and discount (a percentage):
export const discount = writable(0)
export const toPay = derived([total, discount], ([$total, $discount]) =>
$total - ($total * $discount) / 100
)
With Fried Rice in the cart (a total of 15), this is what happens:
| Event | total's formula | toPay's formula | $toPay |
|---|---|---|---|
| Add Fried Rice | runs | runs | 15 |
discount.set(10) |
doesn't run | runs | 13.5 |
discount.set(10) again |
doesn't run | doesn't run | 13.5 |
- A formula only runs when its own sources change.
totaldoesn't depend ondiscount, so a new discount doesn't touch it. - A store given the same value (10, then 10 again) tells nobody, so toPay's formula stays idle too.
Derived is read-only
A derived store can only be read (read-only), because it only has subscribe. There is no set, and no update. So total.set(0) ends with this error:
TypeError: total.set is not a function
The total stays $15.00, not $0.00. A derived store's value is always the formula's result from its sources. To change the total, change cart.
📌 Computed only when someone reads it
A derived store only starts working once it has a subscriber (a component that subscribes to it). Its formula runs once when the first subscriber arrives, for example when a component writing {$toPay} is created. After that, the formula runs whenever a source changes. A derived store that no component reads never runs its formula, however often the cart changes. So a derived store with an expensive formula is safe to keep in stores.js: the formula only runs when the store is used.
Exercise: doubled
In the exercise, you use small numbers. The starter already has count = writable(5):
<script>
import { writable, derived } from "svelte/store"
const count = writable(5)
const doubled = derived(count, ($c) => $c * 2)
</script>
<p>{$count} x 2 = {$doubled}</p>
- The paragraph reads
5 x 2 = 10. Both numbers are read from stores:{$count}and{$doubled}. - Writing
<p>5 x 2 = 10</p>does show the same text, but the sentence no longer follows the stores. Changecounttowritable(7), and it still shows10. That's why the checker looks forderived(and{$doubled}in your code.
$derived inside one component
When the derived value is only used by one component, you don't need a store. The $derived rune from the Reactive Declarations lesson is enough, with cart made with $state:
<script>
let cart = $state([{ name: "Fried Rice", price: 15 }])
let total = $derived(cart.reduce((sum, m) => sum + m.price, 0))
</script>
<p>Total: ${total.toFixed(2)}</p>
Same formula, but total is read with no $ and only lives in this component. A derived store is still the right fit for a derived value that many components use through stores.js.
⚠️ A derived store that won't follow, or won't be changed
- Changing a derived store directly.
total.set(0)fails withTypeError: total.set is not a function. Change its source. - A number typed by hand.
<p>5 x 2 = 10</p>happens to be right now, but doesn't follow changes. Read from the stores:{$count} x 2 = {$doubled}. - Forgetting
$in the template.{doubled}shows[object Object], just like any store. - A formula that reads a store without naming it as a source. A derived store only recomputes when a store in its first argument changes. If toPay's formula needs
discount,discountmust be in its source array.
TL;DR: derived(source, formula) from "svelte/store" creates a derived store, a store whose value is computed from other stores, for example total = derived(cart, ($cart) => ...sum of prices). Its formula reruns by itself whenever the source changes, and a derived store is read with {$total} like any store. The source can be an array, as in the toPay store, which uses derived([total, discount], ([$total, $discount]) => ...). A new discount only reruns the formula of toPay, not the formula of total. A derived store is read-only (it can only be read): total.set(0) gives TypeError: total.set is not a function, so its value can't be set from outside. Its formula only runs when it has a subscriber (a component that subscribes to it). For a derived value inside one component, $derived is enough, no store needed. The exercise: const doubled = derived(count, ($c) => $c * 2) and <p>{$count} x 2 = {$doubled}</p>, which shows 5 x 2 = 10.
⚡ derived: a store from other stores
Write:
// stores.js
import { writable, derived } from "svelte/store"
export const cart = writable([])
export const total = derived(cart, ($cart) =>
$cart.reduce((sum, m) => sum + m.price, 0)
)
Meaning: derived(source, formula) (imported from "svelte/store") creates a derived store, a new store whose value is computed from other stores. Here the source is the cart store, which holds items with a price. The formula receives the cart's value and adds up all the prices, and the result becomes the value of total. Every time cart changes, the formula runs again by itself.
⚡ Read with $, like any store
Write:
<p>Total: ${$total.toFixed(2)}</p>
Meaning: A derived store is read with $, like any other store: $total is the total as a number. Not a single line writes to total. The Add button only changes the cart through cart.update(...), and the total follows.
⚡ A derived store is read-only
Guess first: the total is $15.00, then the code runs total.set(0). Does the total become $0.00?
No. A derived store only has subscribe, so what you get is TypeError: total.set is not a function, and the total stays $15.00.
Meaning: A derived store can only be read (read-only). Its value is always the formula's result from its sources. To change the total, change its source, cart.