Skip to content

Commit 7a4556d

Browse files
committed
fix(web): fix mermaid diagram hydration mismatch
Replace module-level idCounter with React useId() hook to generate stable IDs that match between server and client rendering.
1 parent 18cd0e8 commit 7a4556d

File tree

1 file changed

+5
-9
lines changed

1 file changed

+5
-9
lines changed

web/src/components/docs/mdx/mermaid-diagram.tsx

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,18 @@
11
'use client'
22

3-
import { useLayoutEffect, useRef, useState } from 'react'
3+
import { useId, useLayoutEffect, useRef, useState } from 'react'
44

5-
let idCounter = 0
65
let mermaidPromise: Promise<typeof import('mermaid')> | null = null
76
let isInitialized = false
87

9-
function generateUniqueId() {
10-
return `mermaid-${idCounter++}`
11-
}
12-
138
interface MermaidDiagramProps {
149
code: string
1510
className?: string
1611
}
1712

1813
export function MermaidDiagram({ code, className = '' }: MermaidDiagramProps) {
19-
const idRef = useRef(generateUniqueId())
14+
const id = useId()
15+
const mermaidId = `mermaid-${id.replace(/:/g, '-')}`
2016
const containerRef = useRef<HTMLDivElement>(null)
2117
const [error, setError] = useState<string | null>(null)
2218
const [isLoading, setIsLoading] = useState(true)
@@ -51,7 +47,7 @@ export function MermaidDiagram({ code, className = '' }: MermaidDiagramProps) {
5147
}
5248

5349
// Render the diagram with a unique ID each time
54-
const uniqueId = `${idRef.current}-${Date.now()}`
50+
const uniqueId = `${mermaidId}-${Date.now()}`
5551
const { svg } = await mermaid.render(uniqueId, code)
5652

5753
if (containerRef.current) {
@@ -97,7 +93,7 @@ export function MermaidDiagram({ code, className = '' }: MermaidDiagramProps) {
9793
)}
9894
<div
9995
ref={containerRef}
100-
id={idRef.current}
96+
id={mermaidId}
10197
className="mermaid-diagram flex justify-center"
10298
style={{ display: isLoading ? 'none' : 'block' }}
10399
/>

0 commit comments

Comments
 (0)