Adding Reactivity to Our Svelte App
Tags: webdev, programming, javascript, svelte
Published: 2021-01-28 21:36:46

**Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62**

**Subscribe to my email list now at http://jauyeung.net/subscribe/**

Svelte is an up and coming front end framework for developing front end web apps.

It’s simple to use and lets us create results fast.

In this article, we’ll look at how to run code reactivity when variable values change in a Svelte app.

Reactivity
==========

We can add reactivity to our app with the `$` sign. To do this, we write something like:

```
<script>  
  let count = 0;  
  $: doubleCount = count * 2; 
  const handleClick = () => {  
    count += 1;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Increment  
  </button>  
  <p>{count} {doubleCount}</p>  
</main>
```

Then code:

```
$: doubleCount = count * 2;
```

is reactive. This means that this will run with `count` is updated.

The `$:` is a label.

Therefore, when we click the button, both `count` and `doubleCount` will be updated with the latest values.

We can also put a block after the `$:` as follows:

```
<script>  
  let count = 0;  
  let doubleCount = 0;  
  $: {  
    doubleCount = count * 2;  
    console.log(count);  
  } 

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

<main>  
  <button on:click={handleClick}>  
    Increment  
  </button>  
  <p>{count} {doubleCount}</p>  
</main>
```

In the code above, we have the following:

```
$: {  
  doubleCount = count * 2;  
  console.log(count);  
}
```

We run code to update `doubleCount` and log `count` ‘s value in the same block.

Reactivity is triggered by assignment, so array methods like push and splice won’t automatically cause updates.

Therefore, we have to make the assignment event if the method changes the array in-place.

For instance, we can write the following code:

`App.svelte` :

```
<script>  
  let nums = [];  
  let count = 0; 
  const handleClick = () => {  
    nums = [...nums, count];  
    count++;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Add Number  
  </button>  
  <p>{nums.join(', ')}</p>  
</main>
```

In the code above, we have the `handleClick` function, which put the `nums` ‘s existing values in a new array with the spread operator, then we put the current `count` as the last element of the array instead of calling `push` to append `count` to the `nums` array.

Then we increment the `count` .

We should then get a list of numbers separated by commas as we click the Add Number button.

Assignment to properties of arrays and objects work the same way as an assignment to values themselves.

For instance, the following code:

`App.svelte` :

```
<script>  
  let nums = [];  
  let count = 0; 
  const handleClick = () => {  
    nums[nums.length] = count;  
    count++;  
  };  
</script>

<main>  
  <button on:click={handleClick}>  
    Add Number  
  </button>  
  <p>{nums.join(', ')}</p>  
</main>
```

works the same way as the code in the previous example.

The variable must appear on the left-hand side of the assignment operator for the assignment to be reactive.

Therefore, if we want to update a nested property, then we have to do something like the following:

`App.svelte` :

```
<script>  
  let obj = { foo: { bar: "bar" } }; const handleClick = () => {  
    obj.foo.bar = obj.foo.bar === "foo" ? "bar" : "foo";  
  };  
</script><main>  
  <button on:click={handleClick}>  
    Toggle  
  </button>  
  <p>{obj.foo.bar}</p>  
</main>
```

In the code above, if we click the Toggle button, we’ll assign the `obj.foo.bar` property to `'foo'` or `'bar'` depending on the value of `obj.foo.bar` .

Therefore, when we click the Toggle button, it should switch between `foo` and `bar` .

Conclusion
==========

We can make a reactive property that’s derived from another property by writing: `$:` before the expression.

`$:` can also be used with a block.

To update a reactive value, we always have to reassign the value to the existing variable. As long as the variable we’re updating appears on the left side of the assignment expression, it’ll update.