DEV Community

Cover image for Debounce Method for Searching
NISHARGA KABIR
NISHARGA KABIR

Posted on

Debounce Method for Searching

What is Debounce?

Debounce is nothing but a programming pattern for delaying the execution of a function or something...

Why do we use it? or Why is it important?

Look at this code.....

<input type='text' onChange={(e) => console.log(e.target.value)} />

and its output........

Without Debounce

We type simple 2 words but it's calling 14 times!! If we integrate Search API here our API will be called 14 times for these words.

It will be costly for us. That is why the Debounce Method played its role in waiting some time and getting the result.

create a hook or a function for debounce 😎😎

const useDebounced = ({ searchQuery, delay }) => {
        const [debouncedValue, setDebouncedValue] =
            useState(searchQuery);
        useEffect(() => {
            const handler = setTimeout(() => {
                setDebouncedValue(searchQuery);
            }, delay);
            return () => {
                clearTimeout(handler);
            };
        }, [searchQuery, delay]);

        return debouncedValue;
    };
Enter fullscreen mode Exit fullscreen mode

What do we do here...?? as a parameter we need two things searchQuery and delay time..

using useState we set our value here. and later we return it.
we use useEffect for calling this process infinite time changing searchQuery or delay value change it will be calling.

then we use a setTimeout function. its nothing just a prebuild function in javascript which is calling after a certain time.

and clearTimeout is another function for stoping that setTimeout function.

What is the logic behind this setTimeout and clearTimeOut here? Well we want the user to type something... After he writes the first character when he writes another character between the delay time stop calling the setTimeout here. finally return it

Now its time to implement it 🤩🤩

before return your nextjs or react component add this

const [value, setValue] = useState('');

const debouncedValue = useDebounced({ searchQuery: value, delay: 600 });  

console.log(debouncedValue);
Enter fullscreen mode Exit fullscreen mode

and your input field

<input type='text' onChange={(e) => setValue(e.target.value)} />
Enter fullscreen mode Exit fullscreen mode

Let me explain these two things. in inputs we set our values to the state value.
Then calling that function and as parameter pass our e.target.value and a delay time. finally console.log it.

After Apply Debounce

Now see just calling two or three times base on our typing speed this debounce method will call 😍😍

Top comments (0)