Derived Stores — Svelte

derived(source, formula) from "svelte/store" creates a derived store, a store whose value is computed from other stores, for example total = derived(cart…

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

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

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>

$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

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.

What you will learn