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);
}

Explanation

Overriding deriveds is handy for optimistic UI. Declare it with const if it must not be reassigned.

Further reading

Problem with a question

Svelte · Middle · question 2

Test yourself

Take the Svelte · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz