MCPcopy Create free account
hub / github.com/adobe/react-spectrum / useId

Function useId

packages/react-aria/src/utils/useId.ts:40–103  ·  view source on GitHub ↗
(defaultId?: string)

Source from the content-addressed store, hash-verified

38 * @param defaultId - Default component id.
39 */
40export 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;

Callers 15

ComponentFunction · 0.90
usePreviewTriggerFunction · 0.90
useTooltipTriggerFunction · 0.90
useLabelsFunction · 0.90
useSlotId2Function · 0.90
useValueIdFunction · 0.90
useGridListFunction · 0.90
useNumberFieldFunction · 0.90
useSelectableItemFunction · 0.90
useCollectionIdFunction · 0.90
useLabelFunction · 0.90
useGridFunction · 0.90

Calls 6

unregisterMethod · 0.80
pushMethod · 0.80
deleteMethod · 0.80
registerMethod · 0.65
setValueFunction · 0.50
setMethod · 0.45

Tested by 4

ComponentFunction · 0.72
ComponentFunction · 0.72
SlotsUseSlotIdFunction · 0.72
TestFunction · 0.68