javascript / expert
Snippet
Lazy Evaluation of Complex Logic via $derived.by
While $derived is perfect for simple expressions, $derived.by allows for complex, multi-step logic that remains memoized and lazy. It only recalculates when its internal dependencies (like 'rawData') change, and only when 'processedData' is actually accessed in the UI or another effect. This functional approach encapsulates transformation logic directly within the reactivity system without polluting the component's top-level scope.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
let rawData = $state([...]);const processedData = $derived.by(() => {const filtered = rawData.filter(item => item.isActive);const sorted = filtered.sort((a, b) => b.score - a.score);return sorted.map(item => ({...item,formattedScore: `${(item.score * 100).toFixed(2)}%`}));});
svelte
Breakdown
1
const processedData = $derived.by(() => {
Creates a memoized reactive derivation using a function block.
2
rawData.filter(...)
Accessing 'rawData' marks it as a dependency for this derivation.
3
return sorted.map(...)
The final result is returned and cached until a dependency changes.