How to Use Custom Store in Svelte: Simple Guide
custom store by defining an object with subscribe and optional set or update methods. Use writable from svelte/store as a base or build your own to manage reactive state across components.Syntax
A custom store in Svelte must have a subscribe method that allows components to reactively listen to changes. Optionally, it can have set and update methods to change the store's value.
You can create a custom store by returning an object with these methods. The subscribe method takes a callback that runs when the store value changes and returns an unsubscribe function.
import { writable } from 'svelte/store'; function customStore(initialValue) { const { subscribe, set, update } = writable(initialValue); return { subscribe, set, update, reset: () => set(initialValue) // custom method }; }
Example
This example shows a custom counter store with a reset method. Components can subscribe to the store, increment the count, or reset it to the initial value.
import { writable } from 'svelte/store'; function createCounter() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), reset: () => set(0) }; } export const counter = createCounter(); // In a Svelte component: // <script> // import { counter } from './counterStore.js'; // </script> // <button on:click={() => counter.increment()}>Increment</button> // <button on:click={() => counter.reset()}>Reset</button> // <p>Count: {$counter}</p>
Common Pitfalls
One common mistake is forgetting to return the subscribe method in the custom store object, which breaks reactivity. Another is directly modifying the store value without using set or update, which won't notify subscribers.
Also, avoid creating stores inside components if you want shared state; create them in separate files to share across components.
/* Wrong: Missing subscribe method */ function badStore() { let value = 0; return { increment: () => value++ }; } /* Right: Include subscribe and update methods */ import { writable } from 'svelte/store'; function goodStore() { const { subscribe, update } = writable(0); return { subscribe, increment: () => update(n => n + 1) }; }
Quick Reference
| Method | Purpose |
|---|---|
| subscribe(callback) | Listen to store changes, returns unsubscribe function |
| set(value) | Set store to a new value and notify subscribers |
| update(fn) | Update store value based on current value |
| custom methods | Add any extra methods like reset or increment |