Consider this Svelte custom store that counts up every second. What will be logged to the console after 3 seconds?
import { readable } from 'svelte/store'; const counter = readable(0, function start(set) { let count = 0; const interval = setInterval(() => { count += 1; set(count); }, 1000); return () => clearInterval(interval); }); counter.subscribe(value => console.log(value));
The subscribe callback is fired immediately with the initial value 0, then after each set call.
The readable store's subscribe invokes the callback synchronously with the initial value 0 upon subscription. The start function then sets up an interval that calls set with 1 after 1 second, 2 after 2 seconds, and 3 after 3 seconds, logging 0, 1, 2, 3.
Given this custom writable store, what is the final value after the code runs?
import { writable } from 'svelte/store'; function createCounter() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), reset: () => set(0) }; } const counter = createCounter(); counter.increment(); counter.increment(); counter.reset(); counter.increment();
Track each method call and its effect on the store value.
The store starts at 0. Two increments make it 2. Then reset sets it back to 0. Finally, one increment makes it 1.
Which code snippet correctly creates a custom store that holds a number and a derived store that doubles it?
Remember the derived store callback receives the store value as the first argument, often named with a $ prefix in examples.
Option B uses the correct syntax with the derived store callback receiving the value as $num and returning $num * 2. Option B misses the $ prefix which is just a naming convention but valid. Option B and D are also valid syntaxes but the question asks for the correct implementation following common Svelte patterns, which is option B.
Examine this custom store code. Why might it cause a memory leak when used in a Svelte component?
import { readable } from 'svelte/store'; function createTimer() { let count = 0; const interval = setInterval(() => { count += 1; }, 1000); return readable(count, set => { set(count); return () => clearInterval(interval); }); } const timer = createTimer();
Consider when the interval starts and when the cleanup function runs.
The interval is created immediately when createTimer runs, outside the readable start function. The cleanup function returned inside readable only clears the interval when the store is unsubscribed, but since the interval was created before subscription, it never gets cleared properly, causing a memory leak.
Why would you create a custom store with explicit start and stop functions instead of a simple writable store?
Think about when you want to start or stop background tasks based on usage.
Custom stores with start and stop logic allow you to start processes like timers or data fetching only when there are subscribers, and stop them when none remain. This saves resources and improves app performance.