forked from mui/material-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
useControlled.js
48 lines (42 loc) · 1.88 KB
/
useControlled.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
/* eslint-disable react-hooks/rules-of-hooks, react-hooks/exhaustive-deps */
import * as React from 'react';
export default function useControlled({ controlled, default: defaultProp, name, state = 'value' }) {
const { current: isControlled } = React.useRef(controlled !== undefined);
const [valueState, setValue] = React.useState(defaultProp);
const value = isControlled ? controlled : valueState;
if (process.env.NODE_ENV !== 'production') {
React.useEffect(() => {
if (isControlled !== (controlled !== undefined)) {
console.error(
[
`Material-UI: A component is changing the ${
isControlled ? '' : 'un'
}controlled ${state} state of ${name} to be ${isControlled ? 'un' : ''}controlled.`,
'Elements should not switch from uncontrolled to controlled (or vice versa).',
`Decide between using a controlled or uncontrolled ${name} ` +
'element for the lifetime of the component.',
"The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.",
'More info: https://fb.me/react-controlled-components',
].join('\n'),
);
}
}, [controlled]);
const { current: defaultValue } = React.useRef(defaultProp);
React.useEffect(() => {
if (!isControlled && defaultValue !== defaultProp) {
console.error(
[
`Material-UI: A component is changing the default ${state} state of an uncontrolled ${name} after being initialized. ` +
`To suppress this warning opt to use a controlled ${name}.`,
].join('\n'),
);
}
}, [JSON.stringify(defaultProp)]);
}
const setValueIfUncontrolled = React.useCallback((newValue) => {
if (!isControlled) {
setValue(newValue);
}
}, []);
return [value, setValueIfUncontrolled];
}