Skip to content

Instantly share code, notes, and snippets.

@kentcdodds
Created April 1, 2024 22:22
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kentcdodds/7347b9cb717188db4652a107c829dd22 to your computer and use it in GitHub Desktop.
Save kentcdodds/7347b9cb717188db4652a107c829dd22 to your computer and use it in GitHub Desktop.
import { useSyncExternalStore } from 'react'
/**
* This will call the given callback function whenever the contents of the map
* change.
*/
class ObservableMap extends Map {
constructor(entries) {
super(entries)
this.listeners = new Set()
}
set(key, value) {
const result = super.set(key, value)
this.emitChange()
return result
}
delete(key) {
const result = super.delete(key)
this.emitChange()
return result
}
emitChange() {
for (const listener of this.listeners) {
listener()
}
}
subscribe(listener) {
this.listeners.add(listener)
return () => {
this.listeners.delete(listener)
}
}
}
export const contentCache = new ObservableMap()
export function useContentCache() {
function subscribe(cb) {
return contentCache.subscribe(cb)
}
function getSnapshot() {
return contentCache
}
return useSyncExternalStore(subscribe, getSnapshot)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment