| 38 | * @param defaultId - Default component id. |
| 39 | */ |
| 40 | export function useId(defaultId?: string): string { |
| 41 | let [value, setValue] = useState(defaultId); |
| 42 | let nextId = useRef(null); |
| 43 | |
| 44 | let res = useSSRSafeId(value); |
| 45 | let cleanupRef = useRef(null); |
| 46 | |
| 47 | // These are intentionally disabled the compiler, these functions just read the identity |
| 48 | // of the ref, not the value inside current. |
| 49 | // oxlint-disable-next-line react/react-compiler |
| 50 | let registeredId = registeredIds.get(cleanupRef); |
| 51 | if (registry && registeredId !== res) { |
| 52 | if (registeredId != null) { |
| 53 | // oxlint-disable-next-line react/react-compiler |
| 54 | registry.unregister(cleanupRef); |
| 55 | } |
| 56 | // oxlint-disable-next-line react/react-compiler |
| 57 | registry.register(cleanupRef, res, cleanupRef); |
| 58 | // oxlint-disable-next-line react/react-compiler |
| 59 | registeredIds.set(cleanupRef, res); |
| 60 | } |
| 61 | |
| 62 | if (canUseDOM) { |
| 63 | const cacheIdRef = idsUpdaterMap.get(res); |
| 64 | // oxlint-disable-next-line react/react-compiler |
| 65 | if (cacheIdRef && !cacheIdRef.includes(nextId)) { |
| 66 | // oxlint-disable-next-line react/react-compiler |
| 67 | cacheIdRef.push(nextId); |
| 68 | } else { |
| 69 | // oxlint-disable-next-line react/react-compiler |
| 70 | idsUpdaterMap.set(res, [nextId]); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | useLayoutEffect(() => { |
| 75 | let r = res; |
| 76 | return () => { |
| 77 | // In Suspense, the cleanup function may be not called |
| 78 | // when it is though, also remove it from the finalization registry. |
| 79 | if (registry) { |
| 80 | registry.unregister(cleanupRef); |
| 81 | registeredIds.delete(cleanupRef); |
| 82 | } |
| 83 | idsUpdaterMap.delete(r); |
| 84 | }; |
| 85 | }, [res]); |
| 86 | |
| 87 | // This cannot cause an infinite loop because the ref is always cleaned up. |
| 88 | // eslint-disable-next-line |
| 89 | useEffect(() => { |
| 90 | let newId = nextId.current; |
| 91 | if (newId) { |
| 92 | setValue(newId); |
| 93 | } |
| 94 | |
| 95 | return () => { |
| 96 | if (newId) { |
| 97 | nextId.current = null; |