0
0
Svelteframework~5 mins

Why reactivity drives UI updates in Svelte

Choose your learning style9 modes available
Introduction

Reactivity helps the user interface update automatically when data changes. This makes apps feel fast and smooth without extra work.

When you want the screen to show new information as soon as data changes.
When building interactive forms that update results live as you type.
When you want to keep UI and data in sync without manually changing the page.
When you want to avoid writing extra code to update the display after data changes.
Syntax
Svelte
let count = 0;

// When 'count' changes, Svelte updates the UI automatically
<p>{count}</p>

// To react to changes, use $: label
$: doubled = count * 2;

Variables declared with let are reactive in Svelte.

The $: label runs code whenever referenced reactive variables change.

Examples
The UI shows the name and updates if name changes.
Svelte
let name = 'Alice';

<p>Hello {name}!</p>
The doubled value updates automatically when count changes.
Svelte
let count = 0;

$: doubled = count * 2;

<p>{count} doubled is {doubled}</p>
Clicking the button changes count, and the UI updates instantly.
Svelte
let count = 0;

function increment() {
  count += 1;
}

<button on:click={increment}>Add 1</button>
<p>Count: {count}</p>
Sample Program

This Svelte component shows a button and two numbers. When you click the button, count increases by one. The UI updates automatically to show the new count and its double. This happens because Svelte tracks changes to count and updates the parts of the page that use it.

Svelte
<script>
  let count = 0;
  
  function increment() {
    count += 1;
  }

  $: doubled = count * 2;
</script>

<button on:click={increment} aria-label="Add one to count">Add 1</button>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
OutputSuccess
Important Notes

Reactivity in Svelte means you don't have to write extra code to update the UI.

Use the $: label to create reactive statements that run when data changes.

Always declare reactive variables with let to allow updates.

Summary

Reactivity keeps the UI and data in sync automatically.

Svelte updates only the parts of the page that depend on changed data.

This makes apps faster and easier to build.