Created
April 1, 2024 22:22
-
-
Save kentcdodds/7347b9cb717188db4652a107c829dd22 to your computer and use it in GitHub Desktop.
This file contains 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' | |
/** | |
* 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