Created
November 6, 2024 16:05
-
-
Save g4rcez/bf29caf79cc4bf7183c1cf16face8a40 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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