0 day streak
javascript / expert
Snippet

Multi-Step Derivations with $derived.by

While standard $derived is used for simple expressions, $derived.by accepts a function body. This is essential for expert-level performance when performing complex calculations that require temporary variables or conditional branches while remaining reactive.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
let rawScores = $state([85, 92, 78]);
let stats = $derived.by(() => {
const sum = rawScores.reduce((a, b) => a + b, 0);
const average = sum / rawScores.length;
return {
average,
grade: average > 90 ? 'A' : 'B'
};
});
svelte
Breakdown
1
$derived.by(() => { ... })
Creates a reactive computation that can contain multiple statements and local variables.
2
return { average, grade }
The return value becomes the read-only reactive value of the 'stats' variable.