javascript / intermediate
Snippet
Reactive Data Transformation with Derived Stores
Derived stores create a new reactive value based on one or more existing stores. This keeps your state logic encapsulated and ensures that downstream calculations stay synchronized automatically.
snippet.js
1
2
3
4
5
6
7
8
9
10
import { writable, derived } from 'svelte/store';export const user = writable({ name: 'Lukas', points: 150 });export const userLevel = derived(user, ($user) => {if ($user.points > 100) return 'Gold';return 'Silver';});// Usage: $userLevel will update automatically when user changes
svelte
Breakdown
1
export const userLevel = derived(user, ($user) => {
Creates a new store that depends on the 'user' store and takes its current value as an argument.
2
return 'Gold';
The logic inside the callback determines the value of the derived store.
3
// Usage: $userLevel
The derived store is accessed with the $ prefix for automatic reactive updates.