DEV Community

Rick1196
Rick1196

Posted on

How to debounce a input text on React

Let's explain what a debounce function

A debounce function does not execute at call time, it waits a specific number of times to be executed if the function it's called again before being executed, the time restarts, this will happen N number of times until the function can execute

How can I achieve this with react?

First we need to check how the setTimeout function works

This function allows us to execute a block of code after a certain amount of time, it returns a unique identifier which will allow us to clear that time out every time we call our function with the help of another function called clearTimeout which gets an identifier of the time out

All this is possible thanks to the global scope of javascript, if want to learn more about this, you can check the official documentation

Now we need to build our debounce function

  1. Let's store the ID of the timeout
    let timeoutID  = null
Enter fullscreen mode Exit fullscreen mode

A varaible with no value on it

  1. Let's build the function that will clear the time out and set the new one
const debounceFunction = (params) =>{
    clearTimeout(timeoutID);// the timeout will be removed, so the code won't be executed
    timeoutID = setTimeout({ // set the new timeout
        //...your custom code
    },500)
}
Enter fullscreen mode Exit fullscreen mode

Let's check a full example

Top comments (1)

Collapse
 
brense profile image
Rense Bakker

Since React 18 there's also a built-in hook for this called useDeferredValue: beta.reactjs.org/reference/react/u...