@clayui/shared
Version:
ClayShared component
46 lines (45 loc) • 1.53 kB
JavaScript
import { useCallback, useRef, useState } from "react";
import warning from "warning";
function useControlledState({
defaultName,
defaultValue,
handleName,
name,
onChange,
value
}) {
const [stateValue, setStateValue] = useState(
defaultValue === void 0 ? value : defaultValue
);
const ref = useRef(value !== void 0);
const wasControlled = ref.current;
const isControlled = value !== void 0;
if (wasControlled !== isControlled) {
console.warn(
`WARN: A component changed from ${wasControlled ? "controlled" : "uncontrolled"} to ${isControlled ? "controlled" : "uncontrolled"}. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled '${name}' prop for the lifetime of the component.`
);
}
ref.current = isControlled;
warning(
!(typeof onChange === "undefined" && typeof value !== "undefined"),
`You provided a '${name}' prop for a component without a handler '${handleName}'. This will render the component with an internal state, if the component is to be uncontrolled, use '${defaultName}'. Otherwise, set the '${handleName}' handler.`
);
const setValue = useCallback(
(value2) => {
if (!isControlled) {
setStateValue(value2);
}
if (onChange) {
onChange(value2);
}
},
[]
);
if (!isControlled) {
value = stateValue;
}
return [value, setValue, !isControlled];
}
export {
useControlledState
};