Created
July 30, 2024 16:18
-
-
Save satyam4p/0c8307bb157ddc74f1275643a08fdbd2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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