Skip to content

Commit 24ee392

Browse files
authoredMar 28, 2025··
fix(react): update unhead context on initial <Head> render (#534)
* fix(react): Ensure `<Head>` updates context immediately for SSR compatibility * fix(react): update unhead context on initial render in <Head> component By leverating useRef initial value
1 parent fa8351a commit 24ee392

File tree

1 file changed

+17
-24
lines changed

1 file changed

+17
-24
lines changed
 

‎packages/react/src/components.ts

+17-24
Original file line numberDiff line numberDiff line change
@@ -9,22 +9,10 @@ interface HeadProps {
99
titleTemplate?: string
1010
}
1111

12-
const isBrowser = typeof window !== 'undefined' && typeof document !== 'undefined' && typeof navigator !== 'undefined'
13-
1412
const Head: React.FC<HeadProps> = ({ children, titleTemplate }) => {
15-
const headRef = useRef<ActiveHeadEntry<any> | null>(null)
1613
const head = useUnhead()
1714

18-
useEffect(() => {
19-
return () => {
20-
if (headRef.current?.dispose()) {
21-
headRef.current.dispose()
22-
}
23-
headRef.current = null
24-
}
25-
}, [])
26-
27-
const applyHeadChanges = useCallback(() => {
15+
const getHeadChanges = useCallback(() => {
2816
const input: UseHeadInput = {
2917
titleTemplate,
3018
}
@@ -51,20 +39,25 @@ const Head: React.FC<HeadProps> = ({ children, titleTemplate }) => {
5139
input[type] = data
5240
}
5341
})
54-
55-
if (!headRef.current) {
56-
headRef.current = head.push(input)
57-
}
58-
else {
59-
headRef.current.patch(input)
60-
}
42+
return input
6143
}, [children, titleTemplate])
6244

63-
useEffect(applyHeadChanges, [applyHeadChanges])
45+
const headRef = useRef<ActiveHeadEntry<any> | null>(
46+
head.push(getHeadChanges()),
47+
)
48+
49+
useEffect(() => {
50+
return () => {
51+
if (headRef.current?.dispose) {
52+
headRef.current.dispose()
53+
}
54+
headRef.current = null
55+
}
56+
}, [])
6457

65-
// in ssr, apply changes immediately
66-
if (!isBrowser)
67-
applyHeadChanges()
58+
useEffect(() => {
59+
headRef.current?.patch(getHeadChanges())
60+
}, [getHeadChanges])
6861

6962
return null
7063
}

0 commit comments

Comments
 (0)
Please sign in to comment.