UNPKG

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