Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

the $: label to re run automatically when dependencies change, those dependencies are

Joinyour
determined when Svelte compiles us atcomponent:
Svelte Summit on Nov 11

<script>
export let width;
export let height;

// the compiler knows it should recalculate `area`


// when either `width` or `height` change...
$: area = width * height;

// ...and that it should log the value of `area`


// when _it_ changes
$: console.log(area);
</script>

This works well... until it doesn't. Suppose we refactored the code above:

const multiplyByHeight = (width) => width * height;


$: area = multiplyByHeight(width);

Because the $: area = ... declaration can only 'see' width , it won't be recalculated when
height changes. As a result, code is hard to refactor, and understanding the intricacies of
when Svelte chooses to update which values can become rather tricky beyond a certain level of
complexity.

Svelte 5 introduces the $derived and $effect runes, which instead determine the
dependencies of their expressions when they are evaluated:

<script>
let { width, height } = $props(); // instead of `export let`

const area = $derived(width * height);

$effect(() => {
console.log(area);
});
</script>

As with $state , $derived and $effect can also be used in your .js and .ts files.

Signal boost
SVELTE | Blog
Lik th f k ' t th li ti th t K k t i ht ll l

You might also like