Skip to content

Commit

Permalink
reduce hook usage in production
Browse files Browse the repository at this point in the history
  • Loading branch information
oliviertassinari committed Jan 8, 2020
1 parent f677d46 commit b058ccb
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/material-ui/src/utils/useControlled.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,8 @@ import React from 'react';

const useControlled = ({ controlled, default: defaultProp, name }) => {
const { current: isControlled } = React.useRef(controlled !== undefined);
const { current: defaultValue } = React.useRef(defaultProp);
const [valueState, setValue] = React.useState(() => {
return !isControlled && defaultValue !== undefined ? defaultValue : null;
return !isControlled && defaultProp !== undefined ? defaultProp : null;
});
const value = isControlled ? controlled : valueState;

Expand All @@ -24,7 +23,9 @@ const useControlled = ({ controlled, default: defaultProp, name }) => {
].join('\n'),
);
}
}, [controlled, isControlled, name]);
}, [controlled]);

const { current: defaultValue } = React.useRef(defaultProp);

React.useEffect(() => {
if (defaultValue !== defaultProp) {
Expand Down
10 changes: 10 additions & 0 deletions packages/material-ui/src/utils/useControlled.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,16 @@ describe('useControlled', () => {
);
});

it('warns when switching from controlled to uncontrolled', () => {
const { setProps } = render(<TestComponent value="foobar">{() => null}</TestComponent>);
expect(consoleErrorMock.callCount()).to.equal(0);
setProps({ value: undefined });
expect(consoleErrorMock.callCount()).to.equal(1);
expect(consoleErrorMock.args()[0][0]).to.contains(
'A component is changing a controlled TestComponent to be uncontrolled.',
);
});

it('warns when changing the defaultValue prop after initial rendering', () => {
const { setProps } = render(<TestComponent>{() => null}</TestComponent>);
expect(consoleErrorMock.callCount()).to.equal(0);
Expand Down

0 comments on commit b058ccb

Please sign in to comment.