UNPKG

1.69 kBJavaScriptView Raw
1'use client';
2
3import * as React from 'react';
4import { unstable_useEnhancedEffect as useEnhancedEffect } from '@mui/utils';
5import { CompoundComponentContext } from './useCompoundParent';
6/**
7 * Registers a child component with the parent component.
8 *
9 * @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).
10 * This can be either a value, or a function that generates a value based on already registered siblings' ids.
11 * If a function, it's 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 * @param itemMetadata Arbitrary metadata to pass to the parent component. This should be a stable reference (for example a memoized object), to avoid unnecessary re-registrations.
14 *
15 * @ignore - internal hook.
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