Svelte · Middle · Question 13 of 75

How do you write reusable reactive logic (like a hook) in Svelte 5?

// counter.svelte.js
export function createCounter() {
  let count = $state(0);
  return {
    get count() { return count; },
    increment: () => count++,
  };
}

Explanation

Returning count directly would give a snapshot of the number; a getter keeps reads reactive.

Further reading

Problem with a question

Svelte · Middle · question 13

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