UNPKG

@carbon/ibm-products

Version:
34 lines (32 loc) 1.34 kB
/** * Copyright IBM Corp. 2020, 2026 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ require("../../../_virtual/_rolldown/runtime.js"); let react = require("react"); //#region src/global/js/hooks/useControllableState.ts /** * Copyright IBM Corp. 2025, 2025 * * This source code is licensed under the Apache-2.0 license found in the * LICENSE file in the root directory of this source tree. */ /** * handles controlling state for any component that utilizes controlled and uncontrolled state * @param {T} value - any generic value being held in state * @param {Callback} onChange - a callback function to handle state change when the user puts the component in a controlled state * @returns {[value: T, Callback]} */ function useControllableState(value, onChange) { if (typeof value === "function") throw new TypeError("Functions are not supported"); const [uncontrolledValue, setUncontrolledValue] = (0, react.useState)(value); const onControlledChange = (0, react.useCallback)((controlledValue) => { onChange?.(controlledValue); }, [onChange]); if (typeof onChange === "function") return [value, onControlledChange]; return [uncontrolledValue, setUncontrolledValue]; } //#endregion exports.useControllableState = useControllableState;