Report this

What is the reason for this report?

Introduction to Reactivity in Svelte

Published on May 17, 2019
Introduction to Reactivity in Svelte

We’ve touched on the very first steps to get started with Svelte 3, but in that initial post I purposely omitted to go more in-depth about one of Svelte’s killer features: reactivity.

Reactivity has been all the rage in the past few years for modern JavaScript UI frameworks. Reactivity means that changed values will automatically be reflected in the DOM.

Angular enables reactive programming thanks to RxJS and observables, and Vue.js allows to reactively recompute values with computed properties. As for Svelte, it makes use of a lesser known JavaScript feature, labels, to allow for reactive declarations and reactive statements. This means that you can have certain values be recomputed automatically when certain other values change. This is really powerful, and as you’ll see, Svelte makes it easy as pie. 🥧

Word Counter Component

Let’s see how reactivity in Svelte looks like by building a simple character/word counter example.

Here’s our barebones component:

WordCounter.js
<script>
    let text = '';
</script>

<style>
  textarea {
    width: 100%;
    background: aliceblue;
    font-size: 2rem;
  }
</style>

<textarea bind:value={text} rows="10" />

Nothing too special here, except for the two-way data binding between the value of text and the textarea’s value.

Reactive declarations

Now let’s add a reactive declaration to automatically compute the number of words and characters when the value of the text variable changes:

<script>
  let text = '';

  $: characters = text.length;
  $: words = text.split(' ').length;
</script>

<style>
  textarea {
    width: 100%;
    background: aliceblue;
    font-size: 2rem;
  }
</style>

<textarea bind:value={text} rows="10" />

<p>Character Count: {characters}</p>
<p>Word Count: {words}</p>

We declared two new variables: characters and words, which compute a value based on the value inside of text and which will automatically get recomputed.

The $: part is a label and is perfectly valid JavaScript. Chances are you haven’t used labels in JavaScript before, they are used for edge cases with things like nested for loops. Svelte gives those labelled declarations a special meaning and automatically instruments the declaration for reactivity.

Reactive statements

This reactivity using the special label syntax is not only valid for declaring new variables, but it can also be used to execute statements reactively when a value changes.

Let’s log the value of text to the console when it changes:

<script>
  let text = "";

  $: characters = text.length;
  $: words = text.split(" ").length;

  $: console.log("your text:", text);
</script>

<style>
  textarea {
    width: 100%;
    background: aliceblue;
    font-size: 2rem;
  }
</style>

<textarea bind:value={text} rows="10" />

<p>Character Count: {characters}</p>
<p>Word Count: {words}</p>

Imagine how handy this can be for debugging applications!

Multiple statements

You can group together multiple statements in a block using curly braces:

$: {
  console.log("---");
  console.log("your text:", text);
}

Conditional statements

And you can even use conditionals as your statement:

$: if (text.toLowerCase().includes("see you later alligator")) {
  console.log("Not so soon baboon!");
  text = "";
}

Now every time our text variable contains the string “see you later alligator”, a message is logged to the console and we reset the value for the text variable.

🎩 With this, you can now go on and make your Svelte apps reactive!

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author

Alligator
Alligator
Author
See author profile

Alligator.io is a developer-focused resource that offers tutorials and insights on a wide range of modern front-end technologies, including Angular 2+, Vue.js, React, TypeScript, Ionic, and JavaScript.

Category:
Tags:
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.