0
0
Svelteframework~5 mins

Reactive blocks for side effects in Svelte

Choose your learning style9 modes available
Introduction

Reactive blocks let you run code automatically when some data changes. This helps keep your app updated without extra work.

When you want to update something on the screen after a variable changes.
When you need to run a function automatically after data updates.
When you want to log or track changes in your app state.
When you want to fetch new data after a user input changes.
When you want to trigger animations or effects based on state changes.
Syntax
Svelte
$: {
  // code here runs when used variables change
}
The $: label marks a reactive block in Svelte.
Code inside runs automatically when any variable it uses changes.
Examples
This logs the value of count every time it changes.
Svelte
$: console.log(count);
This recalculates total whenever price or quantity changes.
Svelte
$: {
  total = price * quantity;
}
This shows an alert when count goes above 10.
Svelte
$: {
  if (count > 10) {
    alert('Count is over 10!');
  }
}
Sample Program

This Svelte component shows a button and a count number. When you click the button, count increases by 1. The reactive block logs the new count value automatically every time it changes.

Svelte
<script>
  let count = 0;

  // Reactive block runs when count changes
  $: {
    console.log(`Count changed to ${count}`);
  }

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

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

Reactive blocks run after the component updates the DOM.

Use reactive blocks for side effects, not for returning values.

They help keep your code clean by avoiding manual watchers or event listeners.

Summary

Reactive blocks run code automatically when variables change.

Use $: label to create a reactive block in Svelte.

Great for side effects like logging, alerts, or updating related data.