@mantine/hooks
Version:
A collection of 50+ hooks for state and UI management
43 lines (42 loc) • 1.91 kB
JavaScript
"use client";
const require_use_callback_ref = require("../utils/use-callback-ref/use-callback-ref.cjs");
let react = require("react");
//#region packages/@mantine/hooks/src/use-throttled-callback/use-throttled-callback.ts
function useThrottledCallbackWithClearTimeout(callback, wait) {
const handleCallback = require_use_callback_ref.useCallbackRef(callback);
const latestInArgsRef = (0, react.useRef)(null);
const latestOutArgsRef = (0, react.useRef)(null);
const active = (0, react.useRef)(true);
const waitRef = (0, react.useRef)(wait);
const timeoutRef = (0, react.useRef)(-1);
const clearTimeout = () => window.clearTimeout(timeoutRef.current);
const callThrottledCallback = (0, react.useCallback)((...args) => {
handleCallback(...args);
latestInArgsRef.current = args;
latestOutArgsRef.current = args;
active.current = false;
}, [handleCallback]);
const timerCallback = (0, react.useCallback)(() => {
if (latestInArgsRef.current && latestInArgsRef.current !== latestOutArgsRef.current) {
callThrottledCallback(...latestInArgsRef.current);
timeoutRef.current = window.setTimeout(timerCallback, waitRef.current);
} else active.current = true;
}, [callThrottledCallback]);
const throttled = (0, react.useCallback)((...args) => {
if (active.current) {
callThrottledCallback(...args);
timeoutRef.current = window.setTimeout(timerCallback, waitRef.current);
} else latestInArgsRef.current = args;
}, [callThrottledCallback, timerCallback]);
(0, react.useEffect)(() => {
waitRef.current = wait;
}, [wait]);
return [throttled, clearTimeout];
}
function useThrottledCallback(callback, wait) {
return useThrottledCallbackWithClearTimeout(callback, wait)[0];
}
//#endregion
exports.useThrottledCallback = useThrottledCallback;
exports.useThrottledCallbackWithClearTimeout = useThrottledCallbackWithClearTimeout;
//# sourceMappingURL=use-throttled-callback.cjs.map