@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
35 lines (34 loc) • 1.05 kB
JavaScript
"use client";
let react = require("react");
//#region packages/@mantine/hooks/src/use-debounced-value/use-debounced-value.ts
function useDebouncedValue(value, wait, options = { leading: false }) {
const [_value, setValue] = (0, react.useState)(value);
const mountedRef = (0, react.useRef)(false);
const timeoutRef = (0, react.useRef)(null);
const cooldownRef = (0, react.useRef)(false);
const cancel = (0, react.useCallback)(() => window.clearTimeout(timeoutRef.current), []);
(0, react.useEffect)(() => {
if (mountedRef.current) if (!cooldownRef.current && options.leading) {
cooldownRef.current = true;
setValue(value);
} else {
cancel();
timeoutRef.current = window.setTimeout(() => {
cooldownRef.current = false;
setValue(value);
}, wait);
}
}, [
value,
options.leading,
wait
]);
(0, react.useEffect)(() => {
mountedRef.current = true;
return cancel;
}, []);
return [_value, cancel];
}
//#endregion
exports.useDebouncedValue = useDebouncedValue;
//# sourceMappingURL=use-debounced-value.cjs.map