Skip to content

Commit a5f8d99

Browse files
authored
use memoized registry in RegistryProvider (#255)
* use memoized registry in RegistryProvider * guard against double render in dev
1 parent b753f52 commit a5f8d99

2 files changed

Lines changed: 31 additions & 16 deletions

File tree

.changeset/tame-candles-fail.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@effect-rx/rx-react": patch
3+
---
4+
5+
use memoized registry in RegistryProvider

packages/rx-react/src/RegistryContext.ts

Lines changed: 26 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -35,20 +35,30 @@ export const RegistryProvider = (options: {
3535
readonly timeoutResolution?: number | undefined
3636
readonly defaultIdleTTL?: number | undefined
3737
}) => {
38-
const registry = React.useMemo(() =>
39-
Registry.make({
40-
scheduleTask,
41-
defaultIdleTTL: 400,
42-
...options
43-
}), [])
44-
React.useEffect(() => () => {
45-
registry.dispose()
46-
}, [registry])
47-
return React.createElement(RegistryContext.Provider, {
48-
value: Registry.make({
49-
scheduleTask,
50-
defaultIdleTTL: 400,
51-
...options
52-
})
53-
}, options?.children)
38+
const ref = React.useRef<{
39+
readonly registry: Registry.Registry
40+
timeout?: number | undefined
41+
}>(null)
42+
if (ref.current === null) {
43+
ref.current = {
44+
registry: Registry.make({
45+
scheduleTask: options.scheduleTask ?? scheduleTask,
46+
initialValues: options.initialValues,
47+
timeoutResolution: options.timeoutResolution,
48+
defaultIdleTTL: options.defaultIdleTTL
49+
})
50+
}
51+
}
52+
React.useEffect(() => {
53+
if (ref.current?.timeout !== undefined) {
54+
clearTimeout(ref.current.timeout)
55+
}
56+
return () => {
57+
setTimeout(() => {
58+
ref.current?.registry.dispose()
59+
ref.current = null
60+
}, 500)
61+
}
62+
}, [ref])
63+
return React.createElement(RegistryContext.Provider, { value: ref.current.registry }, options?.children)
5464
}

0 commit comments

Comments
 (0)