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
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

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.