UNPKG

@are-visual/virtual-table

Version:
28 lines 1.03 kB
import { useCallback, useRef, useState } from 'react'; function useControllableValue(props, options) { const { valuePropName = 'value', defaultValue, trigger = 'onChange' } = options ?? {}; const isControlled = valuePropName in props; const value = props[valuePropName]; const initialValue = value ?? defaultValue; const [state, setState] = useState(initialValue); const stateRef = useRef(initialValue); if (isControlled) { // eslint-disable-next-line react-compiler/react-compiler stateRef.current = value; } const onChange = props[trigger]; const updateState = useCallback((action, ...args) => { if (typeof action === 'function') { onChange?.(action(stateRef.current), ...args); } else { onChange?.(action, ...args); } }, [onChange]); if (isControlled) { return [value, updateState]; } return [state, setState]; } export { useControllableValue }; //# sourceMappingURL=useControllableValue.js.map