UNPKG

2.28 kBJavaScriptView Raw
1'use client';
2
3import * as React from 'react';
4import { unstable_useId as useId } from '@mui/utils';
5import { ListContext } from '../useList';
6
7/**
8 * Stabilizes the ListContext value for the MenuItem component, so it doesn't change when sibling items update.
9 *
10 * @param id The id of the MenuItem. If undefined, it will be generated with useId.
11 * @returns The stable ListContext value and the id of the MenuItem.
12 *
13 * Demos:
14 *
15 * - [Menu](https://mui.com/base-ui/react-menu/#hooks)
16 *
17 * API:
18 *
19 * - [useMenuItemContextStabilizer API](https://mui.com/base-ui/react-menu/hooks-api/#use-menu-item-context-stabilizer)
20 */
21export function useMenuItemContextStabilizer(id) {
22 const listContext = React.useContext(ListContext);
23 if (!listContext) {
24 throw new Error('MenuItem: ListContext was not found.');
25 }
26 const itemId = useId(id);
27 const {
28 getItemState,
29 dispatch
30 } = listContext;
31 let itemState;
32 if (itemId != null) {
33 itemState = getItemState(itemId);
34 } else {
35 itemState = {
36 focusable: true,
37 highlighted: false,
38 selected: false
39 };
40 }
41 const {
42 highlighted,
43 selected,
44 focusable
45 } = itemState;
46
47 // The local version of getItemState can be only called with the current Option's value.
48 // It doesn't make much sense to render an Option depending on other Options' state anyway.
49 const localGetItemState = React.useCallback(itemValue => {
50 if (itemValue !== itemId) {
51 throw new Error(['Base UI MenuItem: Tried to access the state of another MenuItem.', `itemValue: ${itemValue} | id: ${itemId}`, 'This is unsupported when the MenuItem uses the MenuItemContextStabilizer as a performance optimization.'].join('/n'));
52 }
53 return {
54 highlighted,
55 selected,
56 focusable
57 };
58 }, [highlighted, selected, focusable, itemId]);
59
60 // Create a local (per MenuItem) instance of the ListContext that changes only when
61 // the getItemState's return value changes.
62 // This makes MenuItems re-render only when their state actually change, not when any MenuItem's state changes.
63 const localContextValue = React.useMemo(() => ({
64 dispatch,
65 getItemState: localGetItemState
66 }), [dispatch, localGetItemState]);
67 return {
68 contextValue: localContextValue,
69 id: itemId
70 };
71}
\No newline at end of file