Skip to content

Commit d7a5937

Browse files
JeremyRHhuozhi
andauthored
fix: Check if adding to registry in useInsertionEffect fails and fall back to useLayoutEffect (#857)
Co-authored-by: Jiachi Liu <inbox@huozhi.im>
1 parent 892ba1c commit d7a5937

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

src/style.js

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,18 @@
1-
import React from 'react'
1+
import React, { useLayoutEffect, useRef } from 'react'
22
import { useStyleRegistry, createStyleRegistry } from './stylesheet-registry'
33
import { computeId } from './lib/hash'
44

55
// Opt-into the new `useInsertionEffect` API in React 18, fallback to `useLayoutEffect`.
66
// https://github.com/reactwg/react-18/discussions/110
7-
const useInsertionEffect = React.useInsertionEffect || React.useLayoutEffect
7+
const useInsertionEffect = React.useInsertionEffect || useLayoutEffect
88

99
const defaultRegistry =
1010
typeof window !== 'undefined' ? createStyleRegistry() : undefined
1111
export default function JSXStyle(props) {
1212
const registry = defaultRegistry ? defaultRegistry : useStyleRegistry()
13+
const insertionEffectCalled = useRef(false)
1314

14-
// If `registry` does not exist, we do nothing here.
15+
// `registry` might not exist while server-side rendering
1516
if (!registry) {
1617
return null
1718
}
@@ -22,6 +23,22 @@ export default function JSXStyle(props) {
2223
}
2324

2425
useInsertionEffect(() => {
26+
// ReactDOM removes all DOM during hydration in certain cases
27+
if (!document.head) {
28+
return
29+
}
30+
registry.add(props)
31+
insertionEffectCalled.current = true
32+
return () => {
33+
insertionEffectCalled.current = false
34+
registry.remove(props)
35+
}
36+
}, [props.id, String(props.dynamic)])
37+
38+
useLayoutEffect(() => {
39+
if (!document.head || insertionEffectCalled.current) {
40+
return
41+
}
2542
registry.add(props)
2643
return () => {
2744
registry.remove(props)

0 commit comments

Comments
 (0)