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

Reactive Variables

Sveip for å vise menyen

One of the most powerful features of Svelte is its built-in reactivity system. Reactive variables allow the user interface to update automatically whenever data changes.

Instead of manually updating the page, Svelte keeps the interface synchronized with your application data automatically.

What Is Reactivity?

Note
Definition

Reactivity means the interface responds to data changes automatically.

For example, if a variable changes from:

let count = 0;

to:

count = 1;

the displayed content updates immediately without manually changing the HTML.

This behavior is one of the core ideas behind modern frontend frameworks.

Creating a Reactive Variable

Open App.svelte and add the following code:

<script>
  let count = 0;

  function increaseCount() {
    count += 1;
  }
</script>

<h1>Counter: {count}</h1>

<button on:click={increaseCount}>
  Increase
</button>

Every time the button is clicked, the value of count changes and the interface updates automatically.

Automatic UI Updates

In traditional JavaScript applications, developers often need to manually update elements in the DOM after changing data.

Svelte removes much of this complexity. When a reactive variable changes, Svelte automatically updates only the parts of the interface that depend on that value.

This makes frontend development feel more natural and efficient.

Reactive State in Real Applications

Reactive variables are used constantly in frontend applications.

For example:

  • Counters;
  • Theme toggles;
  • Form inputs;
  • Search systems;
  • Shopping carts;
  • Dynamic dashboards.

Most interactive UI behavior relies on reactive state updates.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 3. Kapittel 1

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Seksjon 3. Kapittel 1
some-alt