UNPKG

1.13 kBPlain TextView Raw
1import * as React from "react";
2import {
3 useSealedState,
4 SealedInitialState,
5} from "reakit-utils/useSealedState";
6import { unstable_IdContext } from "./IdProvider";
7
8export type unstable_IdState = {
9 /**
10 * ID that will serve as a base for all the items IDs.
11 */
12 baseId: string;
13 /**
14 * @private
15 */
16 unstable_idCountRef: React.MutableRefObject<number>;
17};
18
19export type unstable_IdActions = {
20 /**
21 * Sets `baseId`.
22 */
23 setBaseId: React.Dispatch<React.SetStateAction<string>>;
24};
25
26export type unstable_IdInitialState = Partial<Pick<unstable_IdState, "baseId">>;
27
28export type unstable_IdStateReturn = unstable_IdState & unstable_IdActions;
29
30export function unstable_useIdState(
31 initialState: SealedInitialState<unstable_IdInitialState> = {}
32): unstable_IdStateReturn {
33 const { baseId: initialBaseId } = useSealedState(initialState);
34 const generateId = React.useContext(unstable_IdContext);
35 const idCountRef = React.useRef(0);
36 const [baseId, setBaseId] = React.useState(
37 () => initialBaseId || generateId()
38 );
39 return {
40 baseId,
41 setBaseId,
42 unstable_idCountRef: idCountRef,
43 };
44}