| 1 |
import { useId, useState } from 'react'; |
| 2 |
|
| 3 |
const reactUseId: (() => string) | undefined = typeof useId === 'function' ? useId : undefined; |
| 4 |
|
| 5 |
let counter = 0; |
| 6 |
|
| 7 |
/** |
| 8 |
* SSR-safe ID generation hook. Uses React.useId() when available (React 18+) |
| 9 |
* for guaranteed SSR/CSR match. Falls back to a counter-based approach for React 17. |
| 10 |
*/ |
| 11 |
export const useSSRSafeId: (prefix?: string) => string = reactUseId |
| 12 |
? function useSSRSafeId(prefix = 'pf-'): string { |
| 13 |
return `${prefix}${reactUseId!()}`; |
| 14 |
} |
| 15 |
: function useSSRSafeId(prefix = 'pf-'): string { |
| 16 |
const [id] = useState(() => `${prefix}${++counter}`); |
| 17 |
return id; |
| 18 |
}; |