DEV Community

Discussion on: Debouncing with React Hooks

Collapse
 
strap8 profile image
Nathan Foster • Edited

This makes the most since:

import { useCallback, useRef } from 'react'
export default function useDebounce(func, delay = 400) {
let debounce = useRef(null)
return useCallback(
(...args) => {
const context = this
clearTimeout(debounce.current)
debounce.current = setTimeout(() => {
func.apply(context, args)
}, delay)
},
[func],
)
}

Usage:

const handleWindowResize = useDebounce(SetWindow)

useEffect(() => {
window.addEventListener('resize', handleResize)

handleResize()

return () => {
  window.removeEventListener('resize', handleResize)
}
Enter fullscreen mode Exit fullscreen mode

}, [])