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

Reactive Statements

Scorri per mostrare il menu

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?

Seleziona la risposta corretta

Tutto è chiaro?

Come possiamo migliorarlo?

Grazie per i tuoi commenti!

Sezione 3. Capitolo 2

Chieda ad AI

expand

Chieda ad AI

ChatGPT

Chieda pure quello che desidera o provi una delle domande suggerite per iniziare la nostra conversazione

Sezione 3. Capitolo 2
some-alt