Skip to content

Instantly share code, notes, and snippets.

@max8hine
Last active July 8, 2022 23:55
Show Gist options
  • Save max8hine/54fb9f38f191c0d3efba7e2c59b672b9 to your computer and use it in GitHub Desktop.
Save max8hine/54fb9f38f191c0d3efba7e2c59b672b9 to your computer and use it in GitHub Desktop.
Simplified Code Pattern
Class Store {
#state: { count: 0 };
constractor(initialState) {
if (initialState) this.#state = initialState
}
get state() {
return this.#state
}
set state() {
// requires immutatable update
this.#state = fn(this.state);
this.listeners.forEach(listener => listener())
}
listeners: new Set()
subscribe: (cb) => {
this.listners.add(cb)
return () => this.listners.delete(callback);
}
getSnapshot: () => {
// freeze is optional
const snap = Object.freeze(this.state)
return snap
}
}
// use external store
const Component = () => {
const store = new Store()
const snap = useSyncExternalStore(store.subscribe, store.getSnapshot)
return <div>{snap.count}</div>
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment