Skip to content

Instantly share code, notes, and snippets.

@satyam4p
Created July 30, 2024 16:18
Show Gist options
  • Save satyam4p/0c8307bb157ddc74f1275643a08fdbd2 to your computer and use it in GitHub Desktop.
Save satyam4p/0c8307bb157ddc74f1275643a08fdbd2 to your computer and use it in GitHub Desktop.
import { useCallback, useRef } from "react";
const useDebounceHook = (fn, delay, immediate = false) => {
const timerId = useRef();
const debounce = useCallback(
function () {
let context = this;
let args = arguments;
//check if immediate flag is true so invoke the debounce immediately
let callNow = immediate && !timerId.current;
// base case
// clear the timeout to assign the new timeout to it.
// when event is fired repeatedly then this helps to reset
clearTimeout(timerId.current);
timerId = setTimeout(function () {
// Inside the timeout function, clear the timeout variable
// which will let the next execution run when in 'immediate' mode
timerId.current = null;
// check if the function already ran with the immediate flag
if (!immediate) {
fn.apply(context, args);
}
}, delay);
// immediate mode and no wait timer? Execute the function immediately
if (callNow) fn.apply(context, args);
},
[fn, delay, immediate]
);
return debounce;
};
export default useDebounceHook;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment