How to share state in svelte 5
Function
export function createCounter() {
let count = $state(0);
// you can also derive values
let double = $derived(count * 2);
return {
get count() {
return count;
},
set count(value) {
count = value;
},
increment() {
count++;
},
};
}Export it once in the same file you make it global.
export const counter = createCounter();Or instantiate it in each component make it a new instance per component:
const counter = createCounter();Class
export class Counter {
// make count private
#count = $state(0);
// create property accessors
get count() {
return this.#count;
}
set count(value) {
this.#count = value;
}
}