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 Nov 23, 2023
1 parent 67f6b6c commit 81e1bf8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
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 81e1bf8

Please sign in to comment.