Skip to content

Instantly share code, notes, and snippets.

@Dchole
Last active Sep 27, 2021
Embed
What would you like to do?
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