What are Svelte custom stores and the store contract?

Answer

Any object that implements the store contract is compatible with Svelte's $ auto-subscription syntax. The contract requires a subscribe method that: accepts a subscriber function, calls it immediately with the current value, calls it again whenever the value changes, and returns an unsubscribe function. Custom store example: function createCounter() { const { subscribe, set, update } = writable(0); return { subscribe, increment: () => update(n => n + 1), reset: () => set(0) }; }. The returned object has subscribe (required) plus custom methods. Usage: const counter = createCounter(); $counter; counter.increment();. Custom stores encapsulate state and its update logic, providing a clean API to consumers. They are Svelte's equivalent of custom hooks in React — reusable stateful logic that any component can use.