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