This code creates a writable store 'count' and a derived store 'double' that doubles 'count'. It logs the doubled value whenever 'count' changes.
Execution Table
Step
Action
Base Store Value (count)
Derived Store Value (double)
Subscribers Notified
1
Initialize count with 1
1
undefined
No
2
Create derived store double from count
1
2
No
3
Subscribe to double store
1
2
Yes (logs 2)
4
Update count to 3
3
2
No
5
Derived store recalculates double = 3 * 2
3
6
Yes (logs 6)
6
Update count to 5
5
6
No
7
Derived store recalculates double = 5 * 2
5
10
Yes (logs 10)
8
No more updates
5
10
No
💡 No more updates to base store; derived store value remains stable.
Variable Tracker
Variable
Start
After Step 2
After Step 4
After Step 6
Final
count
1
1
3
5
5
double
undefined
2
6
10
10
Key Moments - 3 Insights
Why does the derived store value update only after the base store changes?
Because derived stores subscribe to base stores and recalculate only when base store values change, as shown between steps 4 and 5 in the execution_table.
Why is the derived store value 'undefined' before creation?
Before the derived store is created, it has no value. At step 1, count is initialized but double is not yet calculated, so it is undefined.
Why do subscribers get notified only after derived store recalculates?
Subscribers are notified only when the derived store value changes, which happens after recalculation triggered by base store updates, as seen in steps 3, 5, and 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5. What is the derived store value 'double'?
A6
B3
C2
Dundefined
💡 Hint
Check the 'Derived Store Value (double)' column at step 5.
At which step does the subscriber first get notified and log a value?
AStep 1
BStep 3
CStep 4
DStep 6
💡 Hint
Look at the 'Subscribers Notified' column for when logging happens.
If the base store 'count' was updated to 10 at step 6 instead of 5, what would be the derived store value at step 7?
A5
B10
C20
D15
💡 Hint
Derived store doubles the base store value as shown in the calculation at step 7.
Concept Snapshot
Derived stores in Svelte listen to one or more base stores.
They compute new values automatically when base stores change.
Use 'derived(baseStore, callback)' to create one.
Subscribers to derived stores get updated values.
Derived stores help keep related data in sync easily.
Full Transcript
Derived stores in Svelte are special stores that depend on other stores. When you create a derived store, you give it one or more base stores and a function that calculates a new value from those base stores. Whenever a base store changes, the derived store recalculates its value and notifies its subscribers. For example, if you have a writable store 'count' and a derived store 'double' that doubles 'count', then changing 'count' automatically updates 'double'. Subscribers to 'double' get the new doubled value. This helps keep your app data consistent without manual updates.