In Svelte, both Context API and stores help share data. Which situation best fits using the Context API instead of stores?
Think about when you want to avoid global reactivity and only pass data down the component tree.
The Context API is best for passing data deeply down the component tree without making it reactive globally. Stores are better for global reactive state.
Given a Svelte writable store used in multiple components, what happens when the store's value changes?
import { writable } from 'svelte/store'; const count = writable(0); // Component A and Component B both subscribe to count count.set(5);
Stores in Svelte are reactive and notify all subscribers on change.
When a store updates, all components subscribed to it automatically update their UI to reflect the new value.
Consider this Svelte code using Context API. Why does the child component not receive the context value?
<script> import { setContext, getContext } from 'svelte'; // Parent.svelte setContext('user', { name: 'Alice' }); </script> <!-- Child.svelte --> <script> const user = getContext('user'); </script> <p>{user.name}</p>
Check where setContext is called in the component lifecycle.
setContext must be called inside the component's script block (not at module top-level) so it runs during component initialization and sets context properly.
Choose the correct syntax to create a readable store that starts a timer and cleans up on unsubscribe.
Remember the readable store callback receives a set function and must return a cleanup function.
Option A correctly uses readable with a set callback and returns a cleanup function to clear the interval.
Given this Svelte writable store holding an object, what is the output after updating a nested property incorrectly?
import { writable } from 'svelte/store'; const user = writable({ name: 'Bob', age: 30 }); user.update(u => { u.age = 31; return u; }); let currentAge; user.subscribe(value => currentAge = value.age)(); console.log(currentAge);
Consider how Svelte detects changes in store values and if mutating nested objects works.
Even though the object is mutated, returning the same object triggers subscribers. So currentAge becomes 31.