Last active
July 8, 2022 23:55
-
-
Save max8hine/54fb9f38f191c0d3efba7e2c59b672b9 to your computer and use it in GitHub Desktop.
Simplified Code Pattern
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
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