Skip to content

Commit

Permalink
Add warning when switching between controlled and uncontrolled
Browse files Browse the repository at this point in the history
  • Loading branch information
mj12albert committed Sep 21, 2023
1 parent febfb2e commit 35f31d6
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions packages/mui-base/src/utils/useControllableReducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
);
}

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>) => {
Expand Down

0 comments on commit 35f31d6

Please sign in to comment.