UNPKG

@spark-ui/hooks

Version:

Common hooks for Spark UI

25 lines 1.03 kB
// src/use-combined-state/useCombinedState.tsx import isEqual from "lodash.isequal"; import { useCallback, useRef, useState } from "react"; function useCombinedState(controlledValue, defaultValue, onChange) { const isControlled = controlledValue !== void 0; const { current: initialValue } = useRef(isControlled ? controlledValue : defaultValue); const [innerValue, setInnerValue] = useState(defaultValue); const value = isControlled ? controlledValue : innerValue; const updater = useCallback( (next, shouldUpdateProp = (prevValue, nextValue) => !isEqual(prevValue, nextValue)) => { const nextValue = typeof next !== "function" ? next : next(value); const shouldUpdate = shouldUpdateProp(value, nextValue); if (shouldUpdate && !isControlled) { setInnerValue(nextValue); } onChange && onChange(nextValue); }, [isControlled, value, onChange] ); return [value, updater, isControlled, initialValue]; } export { useCombinedState }; //# sourceMappingURL=index.mjs.map