If you’re a web developer who wants to learn how to use Svelte reactive variables & functions, then this is the post for you. Today we will learn how reactivity in Svelte works and how it updates our UI when we assign a new value to an existing variable.

We will also take a look at how Svelte Reactive are created with actual pieces of code. Finally, we will learn how to use Functions which update Svelte Reactive statements, and how to use a bit of logic inside our Reactive pieces of code.

Let’s get started!

Reactive Assignments in Svelte

In Svelte, every assignments we make are reactive. For that reason, every time the value we have stored inside of a variable is changed, the entire component will update.

Let’s get started with a simple example. Here we have a variable called peopleCount, that gets initialized with a value of “0”.

<script> export let name; let peopleCount= 0; function addPerson() { personCount = personCount+ 1 } </script> <p>Welcome, {name}!</p> <p>We have {peopleCount} people in our app</p> <button on:click="{addPerson}">Add Person</button>

Notice that we’re embedding it in our HTML inside our second <p> tag:

Every time we click our button, we’re calling the addPerson() function, which in turn increases our peopleCount by one. As opposed to what would happen with vanilla JavaScript, our whole UI is re – rendered every time we make this change.

This is what we mean by reactivity.

However, Svelte’s reactivity is triggered only when an assigned variable is updated directly with an = operator, which can lead to tricky moments. For example, if you push a new value to an existing array, you’ll have to manually update the component for it to show the change.

Marking a Svelte Statement as Reactive

One of the key features of Svelte is that it uses a very simple syntax for declaring reactive variables. For example, the following code snippet shows a straighforward Svelte component that includes two reactive variables:

<script> export let person = "john"; $: upperCaseName = person.toUpperCase(); </script>

In this code, the first statement declares a non-reactive variable called simply “name”. The second statement is reactive in nature, and depends on the first one we’ve declared. What this means is that, every time the value of our first variable gets updated, we are indirectly changing the value of “upperCaseName” as well.

When we use Svelte, reactive statements run just before our component gets loaded every time the values they refer to change. Also, notice that we don’t need to used the reserved keyword let in order to declare our second variable: Svelte does that behind the scenes.

We can use this way of declaring variables together with functions. If, for example, we declare a method called changePerson():

<script> export let person= "john"; $: upperCaseName = person.toUpperCase(); function changePerson() { name = "mike" } </script> <p>Welcome to our app, {person}!</p> <button on:click="{changePerson}">Change Person's Name</button>

In this simple example, the button calls the changePerson() function that in turn modifies the value we have stored in “name”. When this variable changes, it automatically causes the second statement to get triggered and therefore changes the value we had originally saved in upperCaseName.

Can we use logic inside a reactive block?

The answer is yes. If we want to work with more complex pieces of data, we can add any kind of logic (say, a loop or a conditional) inside a $: statement.

For example:

<script> export let person= "john"; let personCount = 0; $: upperCaseName = person.toUpperCase(); $: if (person === "mike") { personCount = 2 } function changePerson() { name = "mike" } </script>

As you can probably figure out by the code, when we call the method changePerson() and update our stored value, the conditional we declared inside our second $: statement gets triggered. This is similar to how computed variables work in other frameworks like Vue or React.

With Svelte, it’s very easy to “listen” to a piece of code, like a function, and make a change to another variable whenever something specific happens. This has the advantage of making our code more declarative, and as a result, simpler to read and understand.

We hope you enjoyed this quick introduction to Svelte’s reactivity model. Stay tuned for more tutorials on Svelte, coming soon! And if you have any questions, feel free to post them in the comments section and we’ll be happy to help.

👋 Hey, I'm Alejandro Rodríguez
Hey there! I'm a front end developer from Spain and a web dev teacher at Ironhack. I've been writing for more than 7 years as a side project, and I love to mix both disciplines whenever I can. Besides working, I'm also passionate about travelling (often with my laptop as a digital nomad) and water sports. What could be better than writing about code in a Caribbean beach, or from a coworking space in an european city?

💬 Leave a comment

Your email address will not be published.

We will never share your email with anyone else.