0
0
Svelteframework~10 mins

Reactive blocks for side effects in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Reactive blocks for side effects
Variable changes
Reactive block runs
Side effect happens
Wait for next change
Back to Variable changes
When a variable changes, the reactive block runs automatically to perform side effects, then waits for the next change.
Execution Sample
Svelte
let count = 0;

$: console.log(`Count is ${count}`);

count = 1;
count = 2;
This code logs the count value whenever it changes using a reactive block.
Execution Table
StepVariable 'count'Reactive Block TriggeredActionOutput
10Yes (initial run)Log 'Count is 0'Count is 0
21YesLog 'Count is 1'Count is 1
32YesLog 'Count is 2'Count is 2
42NoNo action
💡 No more changes to 'count', reactive block does not run again.
Variable Tracker
VariableStartAfter 1After 2Final
count0122
Key Moments - 2 Insights
Why does the reactive block run immediately at the start even before any variable assignment?
The reactive block runs once initially to set up side effects with the current variable value, as shown in Step 1 of the execution_table.
Does the reactive block run if the variable value does not change?
No, the reactive block only runs when the variable changes. Step 4 shows no run because 'count' stayed at 2.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is logged when 'count' changes to 1?
ACount is 2
BCount is 0
CCount is 1
DNo log
💡 Hint
Check Step 2 in the execution_table where 'count' is 1 and the reactive block logs the output.
At which step does the reactive block NOT run?
AStep 4
BStep 1
CStep 3
DStep 2
💡 Hint
Look at the 'Reactive Block Triggered' column in the execution_table for Step 4.
If we set 'count = 2' twice in a row, how many times does the reactive block run?
ATwice
BOnce
CThree times
DNever
💡 Hint
Refer to the variable_tracker and execution_table showing reactive block runs only on value changes.
Concept Snapshot
Svelte reactive blocks run side effects automatically when variables change.
Syntax: $: { /* side effect code */ }
Runs once initially, then on every variable change.
No run if variable value stays the same.
Used for logging, DOM updates, or other side effects.
Full Transcript
In Svelte, reactive blocks start by running once with the current variable values. When a variable changes, the reactive block runs again to perform side effects like logging. If the variable does not change, the block does not run. This behavior helps keep side effects in sync with data changes automatically.