@wordpress/components
Version:
UI components for WordPress.
28 lines (27 loc) • 1.04 kB
JavaScript
import { useCallback, useState } from "@wordpress/element";
// packages/components/src/utils/hooks/use-controlled-value.ts
/**
* Simplified and improved implementation of useControlledState.
*
* @param props
* @param props.defaultValue
* @param props.value
* @param props.onChange
* @return The controlled value and the value setter.
*/
function useControlledValue({ defaultValue, onChange, value: valueProp }) {
const hasValue = typeof valueProp !== "undefined";
const [state, setState] = useState(hasValue ? valueProp : defaultValue);
const value = hasValue ? valueProp : state;
const uncontrolledSetValue = useCallback((nextValue, ...args) => {
setState(nextValue);
onChange?.(nextValue, ...args);
}, [onChange]);
let setValue;
if (hasValue && typeof onChange === "function") setValue = onChange;
else if (!hasValue && typeof onChange === "function") setValue = uncontrolledSetValue;
else setValue = setState;
return [value, setValue];
}
export { useControlledValue };
//# sourceMappingURL=use-controlled-value.mjs.map