What is Reactive Statement in Svelte: Simple Explanation and Example
reactive statement in Svelte is a special syntax using $: that automatically runs code whenever its dependent variables change. It helps keep your component's state and output in sync without manual updates.How It Works
Think of a reactive statement in Svelte like a smart assistant that watches certain variables. Whenever those variables change, the assistant automatically runs the code you wrote to update related values or perform actions.
In Svelte, you write a reactive statement by starting a line with $:. This tells Svelte to track the variables used in that line. When any of those variables change, Svelte reruns the statement to keep everything up to date.
This is similar to how a thermostat reacts to temperature changes: it senses the current temperature and turns heating or cooling on or off automatically. The reactive statement senses variable changes and updates your app accordingly.
Example
This example shows a reactive statement that updates the double variable whenever count changes.
<script> let count = 0; $: double = count * 2; </script> <button on:click={() => count++}>Increase</button> <p>Count: {count}</p> <p>Double: {double}</p>
When to Use
Use reactive statements when you want to automatically update values or run code based on changes to other variables without writing extra functions or event handlers.
Common cases include calculating derived values, updating UI elements, or triggering side effects like logging or fetching data when inputs change.
For example, if you have a form and want to show a live preview or validation message as the user types, reactive statements keep your code clean and responsive.
Key Points
- Reactive statements start with
$:and run automatically when dependencies change. - They help keep your component state and UI in sync without manual updates.
- Use them for derived values, side effects, or any code that depends on reactive variables.
- They make your code simpler and easier to read by reducing boilerplate.