svelte_state.md (850B)
1 # Svelte State 2 3 [How to share state in svelte 5](https://joyofcode.xyz/how-to-share-state-in-svelte-5) 4 5 ## Function 6 7 ```ts 8 export function createCounter() { 9 let count = $state(0); 10 // you can also derive values 11 let double = $derived(count * 2); 12 13 return { 14 get count() { 15 return count; 16 }, 17 set count(value) { 18 count = value; 19 }, 20 increment() { 21 count++; 22 }, 23 }; 24 } 25 ``` 26 27 Export it once in the same file you make it global. 28 29 ```ts 30 export const counter = createCounter(); 31 ``` 32 33 Or instantiate it in each component make it a new instance per component: 34 35 ```ts 36 const counter = createCounter(); 37 ``` 38 39 ## Class 40 41 ```ts 42 export class Counter { 43 // make count private 44 #count = $state(0); 45 46 // create property accessors 47 get count() { 48 return this.#count; 49 } 50 set count(value) { 51 this.#count = value; 52 } 53 } 54 ```