Tutorial

Introduction to Reactivity in Svelte

Published on May 17, 2019
    author

    Alligator.io

    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 authors
    Default avatar
    Alligator.io

    author

    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?

    Ask a questionSearch for more help

    Was this helpful?
     
    Leave a comment
    

    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!

    Try DigitalOcean for free

    Click below to sign up and get $200 of credit to try our products over 60 days!

    Sign up

    Join the Tech Talk
    Success! Thank you! Please check your email for further details.

    Please complete your information!

    Become a contributor for community

    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

    DigitalOcean Documentation

    Full documentation for every DigitalOcean product.

    Resources for startups and SMBs

    The Wave has everything you need to know about building a business, from raising funding to marketing your product.

    Get our newsletter

    Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

    New accounts only. By submitting your email you agree to our Privacy Policy

    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.