UNPKG

@reach/auto-id

Version:

Autogenerate IDs to facilitate WAI-ARIA and server rendering.

45 lines (42 loc) 1.06 kB
"use strict"; /** * @reach/auto-id v0.18.0 * * Copyright (c) 2018-2022, React Training LLC * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */ // src/reach-auto-id.ts import * as React from "react"; import { useIsomorphicLayoutEffect as useLayoutEffect } from "@reach/utils"; var serverHandoffComplete = false; var id = 0; function genId() { return ++id; } var maybeReactUseId = React["useId".toString()]; function useId(providedId) { if (maybeReactUseId !== void 0) { let generatedId = maybeReactUseId(); return providedId ?? generatedId; } let initialId = providedId ?? (serverHandoffComplete ? genId() : null); let [id2, setId] = React.useState(initialId); useLayoutEffect(() => { if (id2 === null) { setId(genId()); } }, []); React.useEffect(() => { if (serverHandoffComplete === false) { serverHandoffComplete = true; } }, []); return providedId ?? id2 ?? void 0; } export { useId };