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

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

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...

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay