Bird
Raised Fist0
Svelteframework~10 mins

Derived stores in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Derived stores
Create base stores
↓
Define derived store with function
↓
Subscribe to base stores
↓
Calculate derived value
↓
Update derived store value
↓
Notify subscribers of derived store
↓
Use derived store in UI
Derived stores listen to base stores, compute new values, and update automatically when base stores change.
Execution Sample
Svelte
import { writable, derived } from 'svelte/store';

const count = writable(1);
const double = derived(count, $count => $count * 2);

double.subscribe(value => console.log(value));
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
StepActionBase Store Value (count)Derived Store Value (double)Subscribers Notified
1Initialize count with 11undefinedNo
2Create derived store double from count12No
3Subscribe to double store12Yes (logs 2)
4Update count to 332No
5Derived store recalculates double = 3 * 236Yes (logs 6)
6Update count to 556No
7Derived store recalculates double = 5 * 2510Yes (logs 10)
8No more updates510No
💡 No more updates to base store; derived store value remains stable.
Variable Tracker
VariableStartAfter Step 2After Step 4After Step 6Final
count11355
doubleundefined261010
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.

Practice

(1/5)
1. What is the main purpose of a derived store in Svelte?
easy
A. To create a new store that automatically updates based on other stores
B. To store static values that never change
C. To replace writable stores with simpler syntax
D. To handle user input events directly

Solution

  1. Step 1: Understand what derived stores do

    Derived stores create new values that depend on one or more other stores.
  2. Step 2: Identify the main purpose

    They automatically update when the original stores change, reflecting combined or transformed data.
  3. Final Answer:

    To create a new store that automatically updates based on other stores -> Option A
  4. Quick Check:

    Derived stores update automatically = B [OK]
Hint: Derived stores react to other stores' changes automatically [OK]
Common Mistakes:
  • Thinking derived stores hold static values
  • Confusing derived with writable stores
  • Believing derived stores handle events
2. Which of the following is the correct syntax to create a derived store from two stores a and b?
easy
A. const c = derived(a, b, (a, b) => a + b);
B. const c = derived([a, b], ([$a, $b]) => $a + $b);
C. const c = derived(a, (a, b) => a + b);
D. const c = derived([a, b], (a, b) => a + b);

Solution

  1. Step 1: Recall derived store syntax

    Derived stores take an array of stores and a callback with destructured values.
  2. Step 2: Match correct syntax

    The callback receives an array destructured as [$a, $b] to access current values.
  3. Final Answer:

    const c = derived([a, b], ([$a, $b]) => $a + $b); -> Option B
  4. Quick Check:

    Array + destructured callback = A [OK]
Hint: Use array and destructure values in derived callback [OK]
Common Mistakes:
  • Passing stores as separate arguments instead of array
  • Not destructuring the values in callback
  • Using wrong parameter order in callback
3. Given the following code, what will be logged to the console after a.set(3) is called?
import { writable, derived } from 'svelte/store';
const a = writable(1);
const b = writable(2);
const sum = derived([a, b], ([$a, $b]) => $a + $b);
sum.subscribe(value => console.log(value));
a.set(3);
medium
A. 1, 2, 3
B. 3, 2, 5
C. 3, 5, 5
D. 3, 5

Solution

  1. Step 1: Understand initial subscription output

    When subscribing, the current derived value is logged immediately: 1 + 2 = 3.
  2. Step 2: Update store a to 3 and check derived value

    After a.set(3), derived recalculates: 3 + 2 = 5, which is logged.
  3. Final Answer:

    3, 5 -> Option D
  4. Quick Check:

    Initial + updated sum = 3, 5 [OK]
Hint: Derived logs initial and updated values on subscription [OK]
Common Mistakes:
  • Expecting multiple logs before subscription
  • Confusing store values with derived values
  • Missing initial subscription log
4. What is wrong with this derived store code?
import { writable, derived } from 'svelte/store';
const count = writable(0);
const double = derived(count, value => value * 2, 0);
medium
A. There is no error; this code is correct
B. The callback function should destructure the value as an array
C. The derived store must be created from an array of stores, not a single store
D. The third argument (0) is invalid for derived stores

Solution

  1. Step 1: Check derived store syntax for single store

    Derived stores can take a single store and a callback with the value directly.
  2. Step 2: Understand the third argument

    The third argument is the initial value before the first store value arrives, which is valid.
  3. Final Answer:

    There is no error; this code is correct -> Option A
  4. Quick Check:

    Single store + initial value allowed = A [OK]
Hint: Single store derived can have initial value as third argument [OK]
Common Mistakes:
  • Thinking callback must destructure array always
  • Believing derived needs array even for one store
  • Assuming third argument is invalid
5. You have two writable stores: firstName and lastName. You want to create a derived store fullName that updates automatically and trims whitespace from both names before combining. Which code correctly implements this?
hard
A. const fullName = derived([firstName, lastName], (firstName, lastName) => firstName.trim() + ' ' + lastName.trim());
B. const fullName = derived([firstName, lastName], ([$firstName, $lastName]) => $firstName + ' ' + $lastName);
C. const fullName = derived([firstName, lastName], ([$firstName, $lastName]) => `${$firstName.trim()} ${$lastName.trim()}`);
D. const fullName = derived(firstName, $firstName => $firstName.trim() + ' ' + lastName);

Solution

  1. Step 1: Use array of stores and destructure values

    Derived stores with multiple sources require an array and destructuring in the callback.
  2. Step 2: Trim both values before combining

    Use trim() on both $firstName and $lastName before concatenation.
  3. Final Answer:

    const fullName = derived([firstName, lastName], ([$firstName, $lastName]) => `${$firstName.trim()} ${$lastName.trim()}`); -> Option C
  4. Quick Check:

    Array + destructure + trim both = D [OK]
Hint: Destructure array stores and trim inside derived callback [OK]
Common Mistakes:
  • Not trimming both names
  • Passing stores separately, not as array
  • Not destructuring values in callback
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard