UNPKG

@carbon/ibm-products

Version:

Carbon for IBM Products

33 lines (28 loc) 1.08 kB
/** * Copyright IBM Corp. 2020, 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. */ 'use strict'; var React = require('react'); /** * 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] = React.useState(value); const onControlledChange = React.useCallback(controlledValue => { onChange?.(controlledValue); }, [onChange]); if (typeof onChange === 'function') { return [value, onControlledChange]; } return [uncontrolledValue, setUncontrolledValue]; } exports.useControllableState = useControllableState;