Files
Echoion/EchoionWeb/frontend/src/lib/store.ts
T
faumaray bdd69f0aad update
Signed-off-by: faumaray <faumaray@gmail.com>
2026-07-25 23:44:48 +03:00

37 lines
856 B
TypeScript

// Minimal external store + useSyncExternalStore hook. One immutable snapshot
// for the whole app state (the vanilla UI re-rendered everything on any
// refresh anyway, so per-field granularity buys nothing at this scale).
import { useSyncExternalStore } from 'react';
export class Store<T> {
private state: T;
private listeners = new Set<() => void>();
constructor(initial: T) {
this.state = initial;
}
get(): T {
return this.state;
}
set(partial: Partial<T>) {
this.state = { ...this.state, ...partial };
this.listeners.forEach((l) => l());
}
subscribe = (listener: () => void): (() => void) => {
this.listeners.add(listener);
return () => this.listeners.delete(listener);
};
}
export function useStore<T>(store: Store<T>): T {
return useSyncExternalStore(
store.subscribe,
() => store.get(),
() => store.get()
);
}