Svelte · Middle · Question 2 of 75
Can you assign to a $derived value (Svelte 5.25+)?
let { post } = $props();
let likes = $derived(post.likes);
async function like() {
likes += 1; // optimistic update
await api.like(post.id);
}- ✓Correct answer: Yes: the assignment temporarily overrides it until its dependencies change and it re-evaluates
- 2No: deriveds are always read-only
- 3Yes, and it permanently disconnects the derived from its expression
Explanation
Overriding deriveds is handy for optimistic UI. Declare it with const if it must not be reassigned.