@wordpress/components
Version:
UI components for WordPress.
58 lines (57 loc) • 2.05 kB
JavaScript
;
Object.defineProperties(exports, {
__esModule: { value: true },
[Symbol.toStringTag]: { value: "Module" }
});
let _wordpress_element = require("@wordpress/element");
let ___values_ts = require("../values.cjs");
// packages/components/src/utils/hooks/use-controlled-state.ts
const defaultOptions = {
initial: void 0,
/**
* Defaults to empty string, as that is preferred for usage with
* <input />, <textarea />, and <select /> form elements.
*/
fallback: ""
};
/**
* Custom hooks for "controlled" components to track and consolidate internal
* state and incoming values. This is useful for components that render
* `input`, `textarea`, or `select` HTML elements.
*
* https://reactjs.org/docs/forms.html#controlled-components
*
* At first, a component using useControlledState receives an initial prop
* value, which is used as initial internal state.
*
* This internal state can be maintained and updated without
* relying on new incoming prop values.
*
* Unlike the basic useState hook, useControlledState's state can
* be updated if a new incoming prop value is changed.
*
* @param currentState The current value.
* @param [options=defaultOptions] Additional options for the hook.
*
* @return The controlled value and the value setter.
*/
function useControlledState(currentState, options = defaultOptions) {
const { initial, fallback } = {
...defaultOptions,
...options
};
const [internalState, setInternalState] = (0, _wordpress_element.useState)(currentState);
const hasCurrentState = (0, ___values_ts.isValueDefined)(currentState);
(0, _wordpress_element.useEffect)(() => {
if (hasCurrentState && internalState) setInternalState(void 0);
}, [hasCurrentState, internalState]);
return [(0, ___values_ts.getDefinedValue)([
currentState,
internalState,
initial
], fallback), (0, _wordpress_element.useCallback)((nextState) => {
if (!hasCurrentState) setInternalState(nextState);
}, [hasCurrentState])];
}
exports.default = useControlledState;
//# sourceMappingURL=use-controlled-state.cjs.map