How to Create a useDebounce Hook in React

How to Create a useDebounce Hook in React

Ferenc Almasi β€’ 2022 January 06 β€’ Read time 2 min read
  • twitter
  • facebook
React

If you would like to create a useDebounce hook in React, you can use setTimeout and clearTimeout together to fire events fewer times and improve the performance of your app:

Copied to clipboard! Playground
const useDebounce = (func, milliseconds) => {
    const time = milliseconds || 400
    let timer

    return event => {
        if (timer) {
            clearTimeout(timer)
        }

        timer = setTimeout(func, time, event)
    }
}

As you can see, this function doesn't use any React hooks internally, so technically it may not be a hook, but it can still help us greatly reduce the number of times an event is fired, such as a scroll or a resize.

It returns a function, so you can wrap your callbacks inside this hook to get the desired effect. By default, it clears the timer every 400ms, but you can also decrease or increase this interval:

Copied to clipboard! Playground
import useDebounce from 'hooks/useDebounce'

const App = () => {
    const scroll = () => console.log('Scrolled without debounce')

    const scrollWithDebounce = useDebounce(() => {
        console.log('Scrolled with debounce fired')
    })

    const scrollWithMoreDebounce = useDebounce(() => {
        console.log('Scrolled with debounce firing every 1000ms')
    }, 1000)

    window.addEventListener('scroll', scroll)
    window.addEventListener('scroll', scrollWithDebounce)
    window.addEventListener('scroll', scrollWithMoreDebounce)
}

In this example, the first function is fired countless times when the user scrolls the window, while the second callback is assigned to the useDebounce hook, which will reduce the number of events fired every 400 milliseconds. The third example also sets the milliseconds to debounce the callback every 1000ms.

If you would like to see it in action, give it a try on Codesandbox

Try the hook on codesandbox
How to Create a useDebounce Hook in React
If you would like to see more Webtips, follow @flowforfrank

If you are interested in reading more about React hooks, see more examples for custom hooks or just learn about the basics, make sure to check out the article below.

All You Need to Know About React Hooks
  • twitter
  • facebook
React
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.