let or const for $derived runes in Svelte?

Asked 28 days ago Viewed 7 times

Variables in JavaScript can be defined using either let or const (ignoring the antiquated var).

In Svelte, it seems that you can define a derived variable (with the $derived) using either let or const without restriction.

Both of these examples work:

let count = $state(0);
let squared = $derived(count * count);
let count = $state(0);
const squared = $derived(count * count);

I'm curious, is there any suggestion as to when let should be used over const, and vice-versa?

0
1 Answer
Sort by
Accepted by Author Posted 25 days ago

You can manually override the value of a $derived variable. If you plan on taking advantage of this, you must use let. Otherwise, use const.

In the example you posted in your question, const should be used since it would never make sense to manually override squared:

let count = $state(0);
const squared = $derived(count * count);

On the other hand, for example, you may want to override the like count on a post if a user likes so as to avoid unnecessarily re-fetching data:

let likeCount = $derived(data.likes);

function likePost() {
    likeCount++;
}

Following this practice allows you to instantly know if a $derived variable can be overridden just by peeking the definition.

1

Your Answer

You Must Log In or Sign Up to Answer Questions