Writable stores let you keep and change data that your Svelte app can use anywhere. They help your app remember things and update the screen automatically.
Writable stores in Svelte
import { writable } from 'svelte/store'; const storeName = writable(initialValue); // To update the store: storeName.set(newValue); // To update based on current value: storeName.update(current => newValue);
writable creates a store you can read and write.
Use set to replace the value, and update to change it based on the current value.
count starting at 0.import { writable } from 'svelte/store'; const count = writable(0);
count store value to 5.count.set(5);
count value by 1.count.update(n => n + 1);This Svelte component uses a writable store count to keep track of a number. Clicking 'Increase' adds 1 to the count. Clicking 'Reset' sets it back to 0. The count value shows on the page and updates automatically.
<script> import { writable } from 'svelte/store'; const count = writable(0); function increment() { count.update(n => n + 1); } function reset() { count.set(0); } </script> <button on:click={increment} aria-label="Increase count">Increase</button> <button on:click={reset} aria-label="Reset count">Reset</button> <p>Count: {$count}</p>
Use the $ prefix to auto-subscribe to the store in your markup.
Writable stores are reactive: when the value changes, the UI updates automatically.
Always import writable from 'svelte/store' to create writable stores.
Writable stores hold data you can change and share in Svelte apps.
Use set to replace the value and update to change it based on current value.
Use the $ prefix to read the store value reactively in your components.