javascript / expert
Snippet
Reactive State Composition with Custom Stores
Custom stores encapsulate state logic by only exposing specific methods while keeping the 'set' or 'update' methods private. This follows the principle of least privilege and promotes clean architecture.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
import { writable } from 'svelte/store';function createCounter() {const { subscribe, update } = writable(0);return {subscribe,increment: () => update(n => n + 1),reset: () => update(() => 0)};}export const count = createCounter();
svelte
Breakdown
1
const { subscribe, update } = writable(0);
Internalizes the core store functions to manage the private state.
2
return { subscribe, ... }
Only returns the subscription and specific domain-logic methods.
3
export const count = createCounter();
Exports a singleton instance of the store for application-wide use.