Skip to content

Commit

Permalink
feat: use syncExternalStore for state access if available
Browse files Browse the repository at this point in the history
  • Loading branch information
petyosi committed Feb 17, 2024
1 parent c50b23d commit 57928bd
Showing 1 changed file with 21 additions and 1 deletion.
22 changes: 21 additions & 1 deletion src/react-urx/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,25 @@ export function systemToComponent<SS extends AnySystemSpec, M extends SystemProp
/**
* Returns the value emitted from the stream.
*/
const useEmitterValue = <K extends keyof S, V = S[K] extends StatefulStream<infer R> ? R : never>(key: K) => {
const useEmitterValue18 = <K extends keyof S, V = S[K] extends StatefulStream<infer R> ? R : never>(key: K) => {
const system = React.useContext(Context)
const source: StatefulStream<V> = system[key]

const cb = React.useCallback(
(c: () => void) => {
return u.subscribe(source, c)
},
[source]
)

return React.useSyncExternalStore(
cb,
() => u.getValue(source),
() => u.getValue(source)
)
}

const useEmitterValueLegacy = <K extends keyof S, V = S[K] extends StatefulStream<infer R> ? R : never>(key: K) => {
const system = React.useContext(Context)
const source: StatefulStream<V> = system[key]

Expand All @@ -279,6 +297,8 @@ export function systemToComponent<SS extends AnySystemSpec, M extends SystemProp
return value
}

const useEmitterValue = React.version.startsWith('18') ? useEmitterValue18 : useEmitterValueLegacy

const useEmitter = <K extends keyof S, V = S[K] extends Stream<infer R> ? R : never>(key: K, callback: (value: V) => void) => {
const context = React.useContext(Context)
const source: Stream<V> = context[key]
Expand Down

0 comments on commit 57928bd

Please sign in to comment.