Last active
September 27, 2021 15:35
-
-
Save Dchole/b1519992517183ddb450790f7f8e7377 to your computer and use it in GitHub Desktop.
Debouncing with React hooks
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 { useEffect, useRef } from "react" | |
/** | |
* @callback requestCallback | |
* @param {any[]} args - arguments passed into callback | |
*/ | |
/** | |
* Debounce function to reduce number executions | |
* @param {requestCallback} cb - callback function to be executed | |
* @param {number} wait - number of milliseconds to delay function execution | |
* @param {any[]} deps - dependency array | |
*/ | |
const useDebounce = (cb, wait = 800, deps = []) => { | |
const timerRef = useRef(null) | |
useEffect(() => { | |
clearTimeout(timerRef.current) | |
timerRef.current = setTimeout(() => { | |
cb.apply(this, deps) | |
}, wait) | |
return () => clearTimeout(timerRef.current) | |
/** used JSON.stringify(deps) instead of just deps | |
* because passing an array as a dependency causes useEffect | |
re-render infinitely | |
* @see {@link https://github.com/facebook/react/issues/14324} | |
*/ | |
/* eslint-disable react-hooks/exhaustive-deps */ | |
}, [cb, wait, JSON.stringify(deps)]) | |
} | |
export default useDebounce |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment