0
0
SvelteHow-ToBeginner · 3 min read

How to Declare Reactive Variable in Svelte: Simple Guide

In Svelte, declare a reactive variable by prefixing its assignment with $:. This tells Svelte to re-run the code whenever the variables it depends on change, making the variable update automatically.
📐

Syntax

Use the $: label before a variable assignment to make it reactive. This means Svelte will re-run this code whenever any variable it uses changes.

Example parts:

  • $: - marks the statement as reactive
  • variable = expression; - the reactive assignment
svelte
$: reactiveVariable = someValue + 1;
💻

Example

This example shows a counter and a reactive variable that doubles the count. When you click the button, the count updates and the doubled value updates automatically.

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

<button on:click={() => count++}>Increment</button>
<p>Count: {count}</p>
<p>Doubled: {doubled}</p>
Output
Count: 0 Doubled: 0 (Clicking Increment updates Count and Doubled accordingly)
⚠️

Common Pitfalls

Common mistakes when declaring reactive variables in Svelte include:

  • Forgetting the $: label, so the variable won't update reactively.
  • Using reactive declarations for complex logic that should be in functions or stores.
  • Trying to assign reactive variables inside functions without $:, which won't trigger updates.
svelte
/* Wrong way: no $: label, won't update reactively */
let count = 0;
let doubled = count * 2;

/* Right way: with $: label for reactivity */
$: doubled = count * 2;
📊

Quick Reference

Remember these tips for reactive variables in Svelte:

  • Use $: before assignments to make them reactive.
  • Reactive statements run whenever their dependencies change.
  • Use reactive variables to keep UI in sync automatically.

Key Takeaways

Prefix variable assignments with $: to make them reactive in Svelte.
Reactive variables update automatically when their dependencies change.
Without $:, variables do not update reactively.
Use reactive declarations for simple derived values, not complex logic.
Reactive variables help keep your UI in sync with state changes.