Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Oppiskele Reactive Statements | Reactivity and User Interaction
Introduction to Svelte

Reactive Statements

Pyyhkäise näyttääksesi valikon

Reactive variables allow the interface to update automatically when data changes. Reactive statements take this idea even further by allowing values to react to other values automatically.

This makes it easier to keep related data synchronized inside your application.

What Are Reactive Statements?

Reactive statements automatically run whenever the values they depend on change.

In Svelte, reactive statements use the $: syntax.

For example:

<script>
  let price = 20;
  let quantity = 3;

  $: total = price * quantity;
</script>

<h1>Total: ${total}</h1>

Whenever price or quantity changes, the total value updates automatically.

Why Reactive Statements Are Useful

In many applications, some values depend on other pieces of data.

For example:

  • Shopping cart totals;
  • Filtered lists;
  • Form validation;
  • Calculated statistics;
  • Dynamic UI labels.

Reactive statements help developers avoid manually recalculating values every time data changes.

Updating Reactive Data

Add buttons to change the quantity:

<script>
  let price = 20;
  let quantity = 1;

  $: total = price * quantity;

  function increaseQuantity() {
    quantity += 1;
  }
</script>

<h2>Quantity: {quantity}</h2>
<h2>Total: ${total}</h2>

<button on:click={increaseQuantity}>
  Add Item
</button>

Each time the quantity changes, the total updates automatically.

Keeping Data Synchronized

Reactive statements make applications easier to maintain because related values stay synchronized automatically.

Instead of manually updating every dependent value, Svelte handles the updates behind the scenes.

This reactive workflow is one of the reasons Svelte feels very lightweight and developer-friendly.

question mark

What is the purpose of reactive statements in Svelte?

Valitse oikea vastaus

Oliko kaikki selvää?

Miten voimme parantaa sitä?

Kiitos palautteestasi!

Osio 3. Luku 2

Kysy tekoälyä

expand

Kysy tekoälyä

ChatGPT

Kysy mitä tahansa tai kokeile jotakin ehdotetuista kysymyksistä aloittaaksesi keskustelumme

Osio 3. Luku 2
some-alt