Skip to content
Source
Sign inSign up
fuko/trytanstackdb.com
Open History to see the last commit

store.ts

37 lines1.2 KB

1import { useSyncExternalStore } from "react";
2​
3/**
4 * A tiny observable value for state that lives outside React (the fake API's
5 * settings and request log), so plain modules can read and write it and
6 * components can subscribe to it.
7 */
8export interface Store<T> {
9 get: () => T;
10 set: (next: T | ((previous: T) => T)) => void;
11 subscribe: (listener: () => void) => () => void;
13​
14export function createStore<T>(initial: T): Store<T> {
15 let value = initial;
16 const listeners = new Set<() => void>();
17​
18 return {
19 get: () => value,
20 set: (next) => {
21 const resolved = typeof next === "function" ? (next as (previous: T) => T)(value) : next;
22 if (Object.is(resolved, value)) return;
23 value = resolved;
24 for (const listener of listeners) listener();
25 },
26 subscribe: (listener) => {
27 listeners.add(listener);
28 return () => listeners.delete(listener);
29 },
30 };
32​
33/** Subscribes a component to a store. `select` must return a stable value (or a primitive). */
34export function useStore<T, S = T>(store: Store<T>, select?: (value: T) => S): S {
35 const getSnapshot = () => (select ? select(store.get()) : (store.get() as unknown as S));
36 return useSyncExternalStore(store.subscribe, getSnapshot, getSnapshot);