Skip to content

Instantly share code, notes, and snippets.

@g4rcez
Created November 6, 2024 16:05
Show Gist options
  • Save g4rcez/bf29caf79cc4bf7183c1cf16face8a40 to your computer and use it in GitHub Desktop.
Save g4rcez/bf29caf79cc4bf7183c1cf16face8a40 to your computer and use it in GitHub Desktop.
import { useSyncExternalStore } from "react";
type Fn<T> = (a: T) => unknown
class Store<T extends object> {
private snapshot: [state: T, instance: this];
private subscribers = new Set<Fn<T>>();
constructor(private state: T) {
this.snapshot = [this.state, this];
}
public get = () => {
return this.snapshot;
};
public set = (callback: (t: T) => T) => {
this.state = callback(this.state);
this.snapshot = [this.state, this];
this.subscribers.forEach(subscriber => subscriber(this.state));
};
public subscribe = (instance: Fn<T>) => {
this.subscribers.add(instance);
return () => this.subscribers.delete(instance);
};
}
type GLOBAL_STATE = {
count: number;
}
declare global {
interface Window {
MY_STATE: Store<GLOBAL_STATE>;
}
}
window.MY_STATE = new Store({ count: 0 });
export const useGlobalStore = () => useSyncExternalStore(window.MY_STATE.subscribe, window.MY_STATE.get);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment