UNPKG

@kiwicom/orbit-components

Version:

Orbit-components is a React component library which provides developers with the easiest possible way of building Kiwi.com’s products.

29 lines (28 loc) 1.01 kB
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray"; import { useState, useEffect, useCallback, useRef } from "react"; export default function useStateWithTimeout(defaultValue, timeout) { var _useState = useState(defaultValue), _useState2 = _slicedToArray(_useState, 2), state = _useState2[0], setState = _useState2[1]; var timeoutRef = useRef(null); var setStateWithTimeout = useCallback(function (value) { if (typeof setTimeout === "function") { timeoutRef.current = setTimeout(function () { timeoutRef.current = null; setState(value); }, timeout); } }, [timeout]); var clearStateTimeout = useCallback(function () { if (timeoutRef.current !== null && typeof clearTimeout === "function") { clearTimeout(timeoutRef.current); } }, []); useEffect(function () { return function () { clearStateTimeout(); }; }, [clearStateTimeout]); return [state, setState, setStateWithTimeout, clearStateTimeout]; }