MCPcopy
hub / github.com/adobe/react-spectrum / useId

Function useId

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

Source from the content-addressed store, hash-verified

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

Callers 15

ComponentFunction · 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
useGridSelectionCheckboxFunction · 0.90

Calls 6

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

Tested by 3

ComponentFunction · 0.72
ComponentFunction · 0.72
SlotsUseSlotIdFunction · 0.72