From e435142b300985f80e76f591d4ecdf700a6eb542 Mon Sep 17 00:00:00 2001 From: Segun Adebayo Date: Sun, 17 Jan 2021 13:17:33 +0400 Subject: [PATCH] fix: ssr issue with auto-id --- .eslintrc | 1 + packages/hooks/src/use-id.ts | 29 +++++++++++++++++++++-------- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/.eslintrc b/.eslintrc index 727e56c2aea..e2ba8591e76 100644 --- a/.eslintrc +++ b/.eslintrc @@ -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", diff --git a/packages/hooks/src/use-id.ts b/packages/hooks/src/use-id.ts index 52570d6ab59..d366fefc1be 100644 --- a/packages/hooks/src/use-id.ts +++ b/packages/hooks/src/use-id.ts @@ -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 @@ -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 } /**