"use strict";
//
// copied from @gravity-ui/components:
// https://github.com/gravity-ui/components/blob/c31e0b98ce866a8b42da93298c83f81dfb8459f7/src/components/DelayedTextInput/hooks/useDelayedValue.ts
//
Object.defineProperty(exports, "__esModule", { value: true });
exports.useDelayedValue = useDelayedValue;
const react_1 = require("react");
/**
 * Debounce-like hook to delay value update.
 * @param value External value that will be eventually replaced by user input.
 * @param onChange Function to update value param after specified delay.
 * @param delay Time to wait after last delayedOnChange invocation before onChange is called.
 * @example
 * const [searchTerm, setSearchTerm] = React.useState('');
 *
 * const {currentValue: userSearchTermInput, delayedOnChange: handleUserSearchTermInput} = useDelayedValue(searchTerm, setSearchTerm);
 */
function useDelayedValue(value, onChange, delay = 200) {
    const [currentValue, setCurrentValue] = (0, react_1.useState)(value);
    const timeoutRef = (0, react_1.useRef)(undefined);
    const delayedOnChange = (0, react_1.useCallback)((nextValue) => {
        setCurrentValue(nextValue);
        window.clearTimeout(timeoutRef.current);
        timeoutRef.current = window.setTimeout(() => {
            onChange(nextValue);
        }, delay);
    }, [delay, onChange]);
    (0, react_1.useEffect)(() => {
        setCurrentValue((currValue) => (currValue === value ? currValue : value));
    }, [value]);
    (0, react_1.useLayoutEffect)(() => {
        return () => {
            window.clearTimeout(timeoutRef.current);
        };
    }, []);
    return {
        currentValue,
        delayedOnChange,
    };
}
//# sourceMappingURL=useDelayedValue.js.map
