Skip to content

Reactive Statements in Svelte

New Course Coming Soon:

Get Really Good at Git

How to work with Reactive Statements in Svelte

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

For example if you have a count variable:

<script>
let count = 0
</script>

and you update it by clicking a button:

<script>
let count = 0

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

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

You can listen for changes on count using the special syntax $: which defines a new block that Svelte will re-run when any variable referenced into it changes.

Here’s an example:

<script>
let count = 0

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

$: console.log(`${count}`)
</script>

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

I used the block:

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

You can write more than one of them:

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

And you can also add a block to group more than one statement:

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

I used a console.log() call in there, but you can update other variables too:

<script>
let count = 0
let double = 0

$: {
  console.log(`the count is ${count}`)
  double = count * 2
  console.log(`double the count is ${double}`)
}
</script>
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my Svelte Handbook

Here is how can I help you: