Svelte: Reactivity Cheat Sheet

Variables

Sometimes a variable is result from a computation, you’ll have to use a reactive declaration:

let count = 0
$: doubled = count * 2

Expressions

<script>
  let num = 0
  $: squared = num * num
  $: cubed = squared * num
</script>
<button on:click={() => num = num + 1}>
  Increment: {num}
</button>
<p>{squared}</p>
<p>{cubed}</p>

Statement

<script>
  $: if (count >= 10) {
    alert('count is dangerously high!')
    count = 9
  }
  let foo, bar, baz
  $: quux = foo + bar
  $: console.log(quux)
  $: {
    // block expression
  }
  $: if (quux > 10) {
    // actually any ->
  } else {
    // js expression
  }
  $: for (let i = 0; i < baz; i++) {
    // any js expression
  }
  // function declaration too
  $: grunt = arg => quux / arg * baz
  $: { // this would also work
    if (quux < 10) break $
    baz++
  }
  $: (async () => { // and even this
    bar = await Promise.resolve(foo%2)
  })()
</script>

Updating objects

Because Svelte’s reactivity is triggered by assignments following code won’t do anything when called:

function addNumber() {
  numbers.push(numbers.length + 1);
}

Unless you add it this assignment:

function addNumber() {
  numbers.push(numbers.length + 1);
  numbers = numbers;
}