Custom store logic lets you create your own way to share and update data in Svelte apps. It helps keep your app organized and reactive.
Custom store logic in Svelte
import { writable } from 'svelte/store'; function createCustomStore(initialValue) { const { subscribe, set, update } = writable(initialValue); return { subscribe, customMethod: () => update(value => /* change value */ value), reset: () => set(initialValue) }; }
The writable function creates a basic store you can build on.
Return an object with subscribe and your custom methods.
import { writable } from 'svelte/store'; function createCounter() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0) }; } export const counter = createCounter();
import { writable } from 'svelte/store'; function createNameStore() { const { subscribe, set } = writable(''); return { subscribe, setName: (name) => set(name), clear: () => set('') }; } export const nameStore = createNameStore();
This Svelte component uses a custom counter store. Buttons call the store's methods to change the count. The count updates on screen automatically.
ARIA labels improve accessibility for screen readers. The count is announced live when it changes.
<script> import { writable } from 'svelte/store'; function createCounter() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), decrement: () => update(n => n - 1), reset: () => set(0) }; } const counter = createCounter(); </script> <button on:click={() => counter.decrement()} aria-label="Decrease count">-</button> <span aria-live="polite" style="margin: 0 1rem;">{$counter}</span> <button on:click={() => counter.increment()} aria-label="Increase count">+</button> <button on:click={() => counter.reset()} aria-label="Reset count" style="margin-left: 1rem;">Reset</button>
Always return subscribe from your custom store so components can react to changes.
Use update to change the store value based on the current value.
Custom methods make your store easier to use and keep logic in one place.
Custom stores let you control how data is shared and changed in Svelte.
They use writable stores and add your own methods.
This keeps your app organized and reactive with simple code.