The next interesting bit about Svelte is the reactive functions. Often code needs to do something in response to a variable change. Svelte makes that easy by automatically rendering the view when a variable is reassigned on the next browser paint. That’s nice but sometimes you need to react to a variable change inside of the script before it gets rendered. For example, if you need to get new data from the backend on the change of a variable.
Svelte also makes that easy by using a clever override on a rarely used Javascript functionality, the labeled statement. In Svelte, the $:
is used to indicate a reactive definition or statement. It looks something like this:
<script>
// reactive definition
$: foo = bar
// reactive statement
$: {
something = anotherThing
}
</script>
The canonical example of this is:
<script>
let count = 0;
$: doubled = count * 2;
$: console.log('the count is ' + count);
</script>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
<button onclick={ () => count += 1}>Increase</button>
An important consideration is when these reactive statements are run. Svelte handles that in a straightforward way. At compile time, Svelte looks at the code and checks each variable that is read to establish the dependencies. Svelte orders the statements to that they run in the order of the dependencies so that if you have $: squared = doubled * doubled
before $: doubled = count * 2
, doubled
is executed first no matter which order the statements are in. If the order can’t be determined by the variables used, then they are executed in the order they are written.
Also notable is that the reactive statements are executed only once. This is to avoid infinite loops and make it easier to understand and write the code.
This simple approach makes it easy to write reactive code in Svelte without additional syntactical sugar.