@renderlesskit/react
Version:
Collection of headless components/hooks that are accessible, composable, customizable from low level to build your own UI & Design System powered by Reakit
75 lines (61 loc) • 2.96 kB
JavaScript
import { useCallback, useRef, useState } from "react";
export function useControlledState(value, defaultValue, onChange) {
var [stateValue, setStateValue] = useState(value || defaultValue);
var ref = useRef(value !== undefined);
var wasControlled = ref.current;
var isControlled = value !== undefined; // Internal state reference for useCallback
var stateRef = useRef(stateValue);
if (wasControlled !== isControlled) {
console.warn("WARN: A component changed from ".concat(wasControlled ? "controlled" : "uncontrolled", " to ").concat(isControlled ? "controlled" : "uncontrolled", "."));
}
ref.current = isControlled;
var setValue = useCallback(function (value) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
var onChangeCaller = function onChangeCaller(value) {
if (onChange) {
if (!Object.is(stateRef.current, value)) {
for (var _len2 = arguments.length, onChangeArgs = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
onChangeArgs[_key2 - 1] = arguments[_key2];
}
onChange(value, ...onChangeArgs);
}
}
if (!isControlled) {
stateRef.current = value;
}
};
if (typeof value === "function") {
// this supports functional updates https://reactjs.org/docs/hooks-reference.html#functional-updates
// when someone using useControlledState calls setControlledState(myFunc)
// this will call our useState setState with a function as well which invokes myFunc and calls onChange with the value from myFunc
// if we're in an uncontrolled state, then we also return the value of myFunc which to setState looks as though it was just called with myFunc from the beginning
// otherwise we just return the controlled value, which won't cause a rerender because React knows to bail out when the value is the same
var updateFunction = function updateFunction(oldValue) {
for (var _len3 = arguments.length, functionArgs = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
functionArgs[_key3 - 1] = arguments[_key3];
}
var interceptedValue = value(isControlled ? stateRef.current : oldValue, ...functionArgs);
onChangeCaller(interceptedValue, ...args);
if (!isControlled) {
return interceptedValue;
}
return oldValue;
};
setStateValue(updateFunction);
} else {
if (!isControlled) {
setStateValue(value);
}
onChangeCaller(value, ...args);
}
}, [isControlled, onChange]); // If a controlled component's value prop changes, we need to update stateRef
if (isControlled) {
stateRef.current = value;
} else {
value = stateValue;
}
return [value, setValue];
}
//# sourceMappingURL=useControlledState.js.map