0
0
Svelteframework~5 mins

Reactive assignments trigger updates in Svelte

Choose your learning style9 modes available
Introduction

Reactive assignments in Svelte automatically update values and the user interface when data changes. This helps keep your app in sync without extra work.

When you want the screen to update automatically after changing a variable.
When you need to calculate a value based on other variables and want it to refresh instantly.
When you want to avoid manually writing code to update the UI after data changes.
Syntax
Svelte
$: variable = expression;

The $: label marks a reactive assignment.

Whenever any value in the expression changes, the assignment runs again.

Examples
This creates a reactive variable doubled that updates when count changes.
Svelte
$: doubled = count * 2;
This updates greeting whenever name changes.
Svelte
$: greeting = `Hello, ${name}!`;
Sample Program

We start with count as 1 and doubled is 2. Then we change count to 3, so doubled updates to 6 automatically.

Svelte
let count = 1;
$: doubled = count * 2;

// Simulate changing count
count = 3;

console.log(doubled);
OutputSuccess
Important Notes

Reactive assignments run immediately when the component starts.

They re-run only when the values they depend on change.

Summary

Use $: to create reactive assignments in Svelte.

They keep your data and UI in sync automatically.

They help write simpler and cleaner code.