Created
August 26, 2024 17:38
-
-
Save MehYam/9031d618a11691c84a078fa2b3ce37ab to your computer and use it in GitHub Desktop.
A React managed state solution in 27 lines of code using useSyncExternalStore and no external dependencies
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 * as React from 'react'; | |
const events = new EventTarget(); | |
type StateInstance<T> = { | |
subscribe: (callback: () => void) => (() => void), | |
getSnapshot: () => T, | |
setter: (t: T) => void, | |
data: T | |
} | |
const store: Record<string, StateInstance<any>> = {}; | |
function useManagedState<T>(key: string, defaultValue: T) { | |
if (!store[key]) { | |
// initialize a state instance for this key | |
store[key] = { | |
subscribe: (callback: () => void) => { | |
events.addEventListener(key, callback); | |
return () => events.removeEventListener(key, callback); | |
}, | |
getSnapshot: () => store[key].data, | |
setter: (t: T) => { | |
store[key].data = t; | |
events.dispatchEvent(new Event(key)); | |
}, | |
data: defaultValue | |
}; | |
} | |
const instance = store[key] as StateInstance<T>; | |
const data = React.useSyncExternalStore(instance.subscribe, instance.getSnapshot); | |
return [data, instance.setter] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage: