UNPKG

1.62 kBJavaScriptView Raw
1import * as React from 'react';
2import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
3import { CompoundComponentContext } from './useCompound';
4
5/**
6 * Registers a child component with the parent component.
7 *
8 * @param id A unique key for the child component. If the `id` is `undefined`, the registration logic will not run (this can sometimes be the case during SSR).
9 * @param itemMetadata Arbitrary metadata to pass to the parent component. This should be a stable reference (e.g. a memoized object), to avoid unnecessary re-registrations.
10 * @param missingKeyGenerator A function that generates a unique id for the item.
11 * It is called with the set of the ids of all the items that have already been registered.
12 * Return `existingKeys.size` if you want to use the index of the new item as the id.
13 *
14 * @ignore - internal hook.
15 */
16
17export function useCompoundItem(id, itemMetadata) {
18 const context = React.useContext(CompoundComponentContext);
19 if (context === null) {
20 throw new Error('useCompoundItem must be used within a useCompoundParent');
21 }
22 const {
23 registerItem
24 } = context;
25 const [registeredId, setRegisteredId] = React.useState(typeof id === 'function' ? undefined : id);
26 useEnhancedEffect(() => {
27 const {
28 id: returnedId,
29 deregister
30 } = registerItem(id, itemMetadata);
31 setRegisteredId(returnedId);
32 return deregister;
33 }, [registerItem, itemMetadata, id]);
34 return {
35 id: registeredId,
36 index: registeredId !== undefined ? context.getItemIndex(registeredId) : -1,
37 totalItemCount: context.totalSubitemCount
38 };
39}
\No newline at end of file