Skip to content

Commit

Permalink
fix: ssr issue with auto-id
Browse files Browse the repository at this point in the history
  • Loading branch information
segunadebayo committed Jan 17, 2021
1 parent 6728f06 commit e435142
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
1 change: 1 addition & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
"import/prefer-default-export": "off",
"no-underscore-dangle": "off",
"no-shadow": "off",
"no-plusplus": "off",
"spaced-comment": "off",
"guard-for-in": "off",
"react/no-danger": "off",
Expand Down
29 changes: 21 additions & 8 deletions packages/hooks/src/use-id.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import * as React from "react"
import { useSafeLayoutEffect } from "./use-safe-layout-effect"

/**
* Credit: https://github.com/reach/reach-ui/blob/develop/packages/auto-id/src/index.tsx
*/
let handoffComplete = false
let id = 0

function genId() {
id += 1
return id
}
const genId = () => ++id

/**
* Reack hook to generate unique id
Expand All @@ -14,9 +15,21 @@ function genId() {
* @param prefix prefix to append before the id
*/
export function useId(idProp?: string, prefix?: string) {
const [uuid] = React.useState(() => genId())
const id = (idProp ?? uuid).toString()
return prefix ? `${prefix}-${id}` : id
const initialId = idProp || (handoffComplete ? genId() : null)
const [uid, setUid] = React.useState(initialId)

useSafeLayoutEffect(() => {
if (uid === null) setUid(genId())
}, [])

React.useEffect(() => {
if (handoffComplete === false) {
handoffComplete = true
}
}, [])

const id = uid != null ? uid.toString() : undefined
return (prefix ? `${prefix}-${id}` : id) as string
}

/**
Expand Down

0 comments on commit e435142

Please sign in to comment.