Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[base-ui] useControllableReducer warns when controlled props become uncontrolled (and vice versa) #39096

Merged
merged 18 commits into from
Dec 6, 2023
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add warning when switching between controlled and uncontrolled
mj12albert committed Nov 28, 2023
commit f90c026fd9e066ada413cf79ecbc34b21943d97a
Original file line number Diff line number Diff line change
@@ -168,7 +168,7 @@ describe('useControllableReducer', () => {
initialState: { make: 'Mazda', model: '3', productionYear: 2022 },
};

function TestComponent(props: { make: string }) {
function TestComponent(props: { make?: string }) {
const [state] = useControllableReducer({
...reducerParameters,
controlledProps: {
27 changes: 27 additions & 0 deletions packages/mui-base/src/utils/useControllableReducer.ts
Original file line number Diff line number Diff line change
@@ -156,6 +156,33 @@ export function useControllableReducer<
actionContext,
} = parameters;

const controlledPropsRef = React.useRef(controlledProps);

if (process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line react-hooks/rules-of-hooks
React.useEffect(() => {
Object.keys(controlledProps).forEach((key) => {
if (
(controlledPropsRef.current as Record<string, unknown>)[key] !== undefined &&
(controlledProps as Record<string, unknown>)[key] === undefined
) {
console.error(
'MUI: useControllableReducer is changing a controlled prop to be uncontrolled',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add the prop name here?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah 👍 I will also pass in the component name too, as useControllableReducer is likely to be unhelpful for the user that needs to see the error ~

);
}

if (
(controlledPropsRef.current as Record<string, unknown>)[key] === undefined &&
(controlledProps as Record<string, unknown>)[key] !== undefined
) {
console.error(
'MUI: useControllableReducer is changing an uncontrolled prop to be controlled',
);
}
});
}, [controlledProps]);
}

// The reducer that is passed to React.useReducer is wrapped with a function that augments the state with controlled values.
const reducerWithControlledState = React.useCallback(
(state: State, action: ActionWithContext<Action, ActionContext>) => {