1- import React from 'react'
1+ import React , { useLayoutEffect , useRef } from 'react'
22import { useStyleRegistry , createStyleRegistry } from './stylesheet-registry'
33import { 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
99const defaultRegistry =
1010 typeof window !== 'undefined' ? createStyleRegistry ( ) : undefined
1111export 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