forked from use-platform/use-platform
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseUniqId.ts
More file actions
28 lines (24 loc) · 840 Bytes
/
useUniqId.ts
File metadata and controls
28 lines (24 loc) · 840 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import { useContext, useState } from 'react'
import { canUseDom } from '../dom-utils'
import { SSRContext, initialContextValue } from '../ssr'
/**
* React-hook for generate uniq identifier.
*
* When using ssr in a project, you must wrap the application in
* `SSRProvider` for id synchronization between the server and the client.
*
* @param customId - Custom uniq id
*
* @example
* const id = useUniqId()
*/
export function useUniqId(customId?: string): string {
const context = useContext(SSRContext)
const [id] = useState(() => `xuniq-${context.id}-${++context.value}`)
console.assert(
canUseDom || context !== initialContextValue,
'When using ssr in a project, you must wrap the application in <SSRProvider>' +
' for id synchronization between the server and the client.',
)
return customId || id
}