Reactive statements in Svelte

How to use reactive statements in Svelte

In Svelte, you can listen to changes in component state and update other variables.

For example, if you have acountChanging:

<script>
let count = 0
</script>

Then you update it by clicking the button:

<script>
let count = 0

const incrementCount = () => { count = count + 1 } </script>

{count} <button on:click={incrementCount}>+1</button>

You can listen to the changescountUse special syntax$:It defines a new block, Svelte will re-run when any of the variables referenced in it change.

This is an example:

<script>
let count = 0

const incrementCount = () => { count = count + 1 }

$: console.log(</span><span style="color:#e6db74">${</span><span style="color:#a6e22e">count</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) </script>

{count} <button on:click={incrementCount}>+1</button>

I used the block:

$: console.log(`${count}`)

You can write more than one of these codes:

<script>
$: console.log(`the count is ${count}`)
$: console.log(`double the count is ${count * 2}`)
</script>

You can also add a block to combine multiple statements:

<script>
$: {
  console.log(`the count is ${count}`)
  console.log(`double the count is ${count * 2}`)
}
</script>

I used the console.log() call there, but you can also update other variables:

<script>
let count = 0
let double = 0

$: { console.log(the count is </span><span style="color:#e6db74">${</span><span style="color:#a6e22e">count</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) double = count * 2 console.log(double the count is </span><span style="color:#e6db74">${</span><span style="color:#66d9ef">double</span><span style="color:#e6db74">}</span><span style="color:#e6db74">) } </script>

Download mine for freeSlim Handbook


More subtle tutorials: