Derived stores let you create new values based on one or more existing stores. They update automatically when the original stores change.
0
0
Derived stores in Svelte
Introduction
You want to combine values from multiple stores into one value.
You need to transform or calculate a value from a store without changing the original.
You want to keep your UI in sync with related data automatically.
You want to avoid repeating the same calculation in many places.
You want to create a read-only store based on other stores.
Syntax
Svelte
import { derived } from 'svelte/store'; const derivedStore = derived( [store1, store2], ([$store1, $store2]) => $store1 + $store2, initialValue );
You pass one or more stores as the first argument (array or single store).
The callback receives the current values of those stores and returns the new value.
Examples
Derived store
double automatically doubles the value of count.Svelte
import { writable, derived } from 'svelte/store'; const count = writable(2); const double = derived(count, $count => $count * 2);
Derived store
sum adds values from two stores a and b.Svelte
import { writable, derived } from 'svelte/store'; const a = writable(3); const b = writable(4); const sum = derived([a, b], ([$a, $b]) => $a + $b);
Derived store
greeting creates a greeting message from name.Svelte
import { writable, derived } from 'svelte/store'; const name = writable('Alice'); const greeting = derived(name, $name => `Hello, ${$name}!`);
Sample Program
This example shows a writable store celsius and a derived store fahrenheit that converts the temperature. When celsius changes, fahrenheit updates automatically.
Svelte
import { writable, derived } from 'svelte/store'; // Create a writable store for temperature in Celsius const celsius = writable(25); // Create a derived store to convert Celsius to Fahrenheit const fahrenheit = derived(celsius, $celsius => ($celsius * 9 / 5) + 32); // Subscribe to both stores and log their values celsius.subscribe(value => console.log(`Celsius: ${value}°C`)); fahrenheit.subscribe(value => console.log(`Fahrenheit: ${value}°F`)); // Change Celsius value to see automatic update celsius.set(30);
OutputSuccess
Important Notes
Derived stores are read-only by default. You cannot set their value directly.
If you only use one store, you can pass it directly instead of an array.
Use derived stores to keep your data logic clean and avoid repeating calculations.
Summary
Derived stores create new values based on other stores.
They update automatically when the original stores change.
Use them to combine, transform, or calculate store data easily.