I previously wrote runes in Svelte 5 needed improvement. One limitation I mentioned was that the $derived()
rune accepted only expressions that evaluate to a value.
This is fine for short pieces of logic, but painful for calculating derived state with multiple steps. There’s no way to split it up without using more than one
$derived
variable.
Well, good news! The Svelte team agrees and has added $derived.by()
. It accepts a callback function and runs it whenever a rune inside changes.
let someBitOfComplicatedDerivedState = $derived.by(() => {
// ... imagine a 20-line anonymous callback here
});
I’m happy the Svelte team made this change. I think it’ll make runes much easier to use for two reasons.
- It lets users avoid writing immediately invoked function expressions, which are ugly and verbose.
let someBitOfComplicatedDerivedState = $derived(
(() => {
// ... imagine a 20-line anonymous callback here
})()
);
- It lets users avoid writing a separate named function to handle the
$derived()
logic, which is also unnecessarily verbose.
function calculateDerivedState() {
// ... imagine a 20-line anonymous callback here
}
let someBitOfComplicatedDerivedState = $derived(calculateDerivedState());
$derived.by()
will help us write less code, which is whole reason I like Svelte. I appreciate the team listening to the community and adding this feature.