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.

32 lines (29 loc) 948 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = useStateWithTimeout; var _react = require("react"); function useStateWithTimeout(defaultValue, timeout) { const [state, setState] = (0, _react.useState)(defaultValue); const timeoutRef = (0, _react.useRef)(null); const setStateWithTimeout = (0, _react.useCallback)(value => { if (typeof setTimeout === "function") { timeoutRef.current = setTimeout(() => { timeoutRef.current = null; setState(value); }, timeout); } }, [timeout]); const clearStateTimeout = (0, _react.useCallback)(() => { if (timeoutRef.current !== null && typeof clearTimeout === "function") { clearTimeout(timeoutRef.current); } }, []); (0, _react.useEffect)(() => { return () => { clearStateTimeout(); }; }, [clearStateTimeout]); return [state, setState, setStateWithTimeout, clearStateTimeout]; }