Reactivity in Svelte

Svelte is a modern JavaScript framework that makes building fast, reactive web applications easy. One of the key features of Svelte is its reactivity system, which allows you to build interactive, responsive user interfaces without having to write complex reactive code.

In this article, I’ll walk you through reactivity in svelte, how it is used, reactive statements, and declarations.

WHAT IS REACTIVITY?

In Svelte, reactivity refers to the automatic updating of the component's state and the component's view (i.e., the component's template) whenever the component's state changes.

Reactivity is made possible by Svelte's reactivity system, which listens for changes to the component's state and automatically updates the component's view whenever a change is detected.

How it works

Svelte's reactivity system tracks dependencies between state variables and reactive functions (i.e., functions that depend on one or more state variables). When the value of a state variable changes, Svelte's reactivity system knows which reactive functions depend on that state variable and automatically re-runs those functions. It allows Svelte to automatically update the component's view whenever the component's state changes.

Let’s take a look at an example:

Imagine you have a variable age and give it a specific value:

<script>
  let age = 50;
</script>

<div>
  <p>{age}</p>
</div>

You the value o want to increase the value of age when we click a button:

<script>
  let age = 50;
  function handleClick() {
    age++;
  }
</script>

<div>
  <p>{age}</p>
  <button on:click={handleClick}>increase age</button>
</div>

In this example above, our component has a state variable called age which is assigned the value 50. The component also has a button that, when clicked, increments the value of age. The component's template also includes a paragraph that displays the current value of age.

Now, because of Svelte's reactivity system, whenever the value of age changes (in this case, when the button is clicked and age is incremented), the component's view is automatically updated to reflect the new value of count. This means that the paragraph will automatically update to show the new value of age without the need for any additional code. This is called reactive assignments.

Let’s move on to reactive declarations.

Reactive declarations

Reactivity in Svelte is based on the concept of reactive declarations. Reactive declarations are a way for you to generate computed data. Reactive declarations are written using the $: syntax. Using the example above, let’s say we want to include our age in our earlier example inside a string and then assign it to a variable. We could do something like this:

<script>
  let age = 50;
  let sentence = ` Hello, are you ${age} years old?`;
  function handleClick() {
    age++;
  }
</script>

<div>
  <p >{age}</p>
  <p >{sentence}</p>

 <button on:click={handleClick}>increase age</button>
</div>

We created a new variable and assigned a string that includes the age.

If we save this and check our browser, we can see it displayed. Still, if we were to press the button that increments our age, it doesn't increase because our variable was created at the time when our age was 50.

So how do we make our sentence update whenever we click our button? That's where the reactive declarations come in. It can be done by replacing our variable like so:

 $: sentence = `Hello, are you ${age} years old?`;

What we are doing here is whenever our variable age, our sentences should also be updated with the new value.

If we take a look at it inside our browser, we can see that it now updates.

Reactivity with reactive statements

Svelte also supports reactive statements. These are similar to reactive declarations but are more powerful. Reactive statements allow you to define more complex behaviors that involve multiple data sources and conditions.

For example:


<script>
  let age = 1;

  $: {
    if (age === 1) {
      console.log("age is one");
    } else {
      console.log("age has a different value");
    }
  }
</script>
<button on:click={() => {age += 1}}>Increment</button>

In the code block above, we define a variable called age and initialize it to 1. We then define a reactive statement using the $: syntax. The reactive statement contains an if/else statement that logs a message to the console based on the value of age.

When the button is clicked, the value of age changes, which triggers the reactive statement. The reactive statement then logs a message to the console based on the new value of age.

Conclusion

Reactivity is a powerful feature of Svelte that allows developers to build dynamic and responsive web applications with ease. With reactive declarations, reactive assignments, and reactive statements, you can define complex UI behaviours that update automatically in response to changes in data.

Resources

Here are resources to aid your learning process: