0
0
Svelteframework~5 mins

Reactive declarations (let) in Svelte

Choose your learning style9 modes available
Introduction

Reactive declarations let your code automatically update when data changes. It helps keep your app in sync without extra work.

When you want to calculate a value based on other variables and update it automatically.
When you need to keep UI elements updated as data changes.
When you want to avoid writing manual event handlers to update related values.
When you want to simplify your code by letting Svelte handle dependencies.
When you want to create derived values that depend on user input or other reactive data.
Syntax
Svelte
let derived = expression;
$: derived = expression;

The $: label marks a reactive declaration.

Whenever variables inside the expression change, the reactive declaration runs again.

Examples
This creates a reactive variable doubled that updates when count changes.
Svelte
let count = 0;
$: doubled = count * 2;
The greeting updates automatically when name changes.
Svelte
let name = 'Alice';
$: greeting = `Hello, ${name}!`;
sum recalculates whenever a or b changes.
Svelte
let a = 5;
let b = 10;
$: sum = a + b;
Sample Program

This Svelte component shows a button with a count. When you click it, count increases. The doubled value updates automatically and shows below.

It uses a reactive declaration $: doubled = count * 2; to keep doubled in sync.

Svelte
<script>
  let count = 1;
  $: doubled = count * 2;

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

<button on:click={increment} aria-label="Increase count">Count: {count}</button>
<p>Doubled value: {doubled}</p>
OutputSuccess
Important Notes

Reactive declarations run after the component initializes and whenever dependencies change.

You can use multiple reactive declarations in one component.

Use let to declare variables that will change; reactive declarations update them automatically.

Summary

Reactive declarations automatically update values when dependencies change.

Use $: before a statement to make it reactive.

This helps keep your UI and data in sync with less code.