DEV Community

Discussion on: Debouncing with React Hooks

Collapse
 
daxsoft profile image
Michael Willian Santos

My aproach is this way:

import { useMemo, useState } from 'react'

/**
 * Debounce a function by time
 * @param {Function} func
 * @param {Number} delay
 */

export default function useDebounce(func, delay) {
    const [id, setId] = useState(null)

    return useMemo(
        (...args) => {
            if (id) {
                clearTimeout(id)
            } else {
                setId(
                    setTimeout(() => {
                        setId(null)
                        func(...args)
                    }, delay)
                )
            }
        },
        [func]
    )
}

Enter fullscreen mode Exit fullscreen mode
Collapse
 
gusyavo profile image
Gustavo

This looks great! Could you give us an example on how to implement it?