@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
35 lines (34 loc) • 991 B
JavaScript
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
//#region packages/@mantine/hooks/src/use-debounced-value/use-debounced-value.ts
function useDebouncedValue(value, wait, options = { leading: false }) {
const [_value, setValue] = useState(value);
const mountedRef = useRef(false);
const timeoutRef = useRef(null);
const cooldownRef = useRef(false);
const cancel = useCallback(() => window.clearTimeout(timeoutRef.current), []);
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
]);
useEffect(() => {
mountedRef.current = true;
return cancel;
}, []);
return [_value, cancel];
}
//#endregion
export { useDebouncedValue };
//# sourceMappingURL=use-debounced-value.mjs.map