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.
Previous
How do you handle forms in SvelteKit with use:enhance?
Next
How does SSR (Server-Side Rendering) work in SvelteKit?
More Svelte / SvelteKit Questions
View all →- Intermediate How does SSR (Server-Side Rendering) work in SvelteKit?
- Intermediate What are SvelteKit adapters?
- Intermediate What is the difference between prerendering, SSR, and CSR in SvelteKit?
- Intermediate How do you manage environment variables in SvelteKit?
- Intermediate What are Svelte actions (use:)?