Skip to content

Instantly share code, notes, and snippets.

@Dchole
Last active September 27, 2021 15:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dchole/b1519992517183ddb450790f7f8e7377 to your computer and use it in GitHub Desktop.
Save Dchole/b1519992517183ddb450790f7f8e7377 to your computer and use it in GitHub Desktop.
Debouncing with React hooks
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