From 8a1cfd42ba7253c97f06cfacfc7663a31530ba82 Mon Sep 17 00:00:00 2001 From: Albert Yu Date: Tue, 22 Oct 2024 14:47:37 +0800 Subject: [PATCH] Move useContext call from hooks to components --- packages/mui-base/src/Tabs/Tab/Tab.tsx | 24 ++++++++++++------- .../mui-base/src/Tabs/Tab/useTab.test.tsx | 12 ++++++++-- packages/mui-base/src/Tabs/Tab/useTab.ts | 22 +++++++++-------- 3 files changed, 38 insertions(+), 20 deletions(-) diff --git a/packages/mui-base/src/Tabs/Tab/Tab.tsx b/packages/mui-base/src/Tabs/Tab/Tab.tsx index 217fef7cbb..805a95aa88 100644 --- a/packages/mui-base/src/Tabs/Tab/Tab.tsx +++ b/packages/mui-base/src/Tabs/Tab/Tab.tsx @@ -4,7 +4,8 @@ import PropTypes from 'prop-types'; import { useTab } from './useTab'; import { useComponentRenderer } from '../../utils/useComponentRenderer'; import type { BaseUIComponentProps } from '../../utils/types'; -import { TabsOrientation } from '../Root/TabsRoot'; +import type { TabsOrientation } from '../Root/TabsRoot'; +import { useTabsRootContext } from '../Root/TabsRootContext'; /** * @@ -20,18 +21,25 @@ const Tab = React.forwardRef(function Tab( props: Tab.Props, forwardedRef: React.ForwardedRef, ) { - const { className, disabled = false, render, value, ...other } = props; + const { className, disabled = false, render, value: valueProp, ...other } = props; - const { selected, getRootProps, orientation } = useTab({ + const { value: selectedValue, getTabPanelId, orientation } = useTabsRootContext(); + + const { selected, getRootProps } = useTab({ ...props, + getTabPanelId, + isSelected: valueProp === selectedValue, rootRef: forwardedRef, }); - const ownerState: Tab.OwnerState = { - disabled, - selected, - orientation, - }; + const ownerState: Tab.OwnerState = React.useMemo( + () => ({ + disabled, + selected, + orientation, + }), + [disabled, selected, orientation], + ); const { renderElement } = useComponentRenderer({ propGetter: getRootProps, diff --git a/packages/mui-base/src/Tabs/Tab/useTab.test.tsx b/packages/mui-base/src/Tabs/Tab/useTab.test.tsx index 7d7e5a3041..451f1e6c49 100644 --- a/packages/mui-base/src/Tabs/Tab/useTab.test.tsx +++ b/packages/mui-base/src/Tabs/Tab/useTab.test.tsx @@ -12,7 +12,11 @@ describe('useTab', () => { it('returns props for root slot', () => { function TestTab() { const rootRef = React.createRef(); - const { getRootProps } = useTab({ rootRef }); + const { getRootProps } = useTab({ + rootRef, + isSelected: true, + getTabPanelId: () => undefined, + }); return