Home  >  Article  >  Web Front-end  >  Detailed discussion on using Debounce in JavaScript and React

Detailed discussion on using Debounce in JavaScript and React

DDD
DDDOriginal
2024-09-30 12:38:02796browse

JavaScript এবং React এ Debounce ব্যবহার সম্পর্কে বিস্তারিত আলোচনা

debounce is a technique in JavaScript and React, which quickly stops repeating a function and executes the function after a specified time. It is mainly used to improve performance, especially when the user performs tasks such as typing or scrolling.

How does Debounce work?

Debounce basically creates a timer and if the same function is triggered repeatedly within a specified time, it cancels the rest of the functions before executing the last function. For example, to make an API call to a server while typing in the search box, instead of calling the server on each key press, the API call can be made after a specified time once typing is complete. This reduces server load and increases application performance.

How to create Debounce in JavaScript?

The

Debounce function is very easy to create:

function debounce(func, delay) {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
            func.apply(this, args);
        }, delay);
    };
}
The debounce function above

does the following:

  • func: The function to be debounced.
  • delay: how long to wait after which the function will run.

example

Suppose we want to make an API call to a search box, when the user finishes typing:

function handleSearch(query) {
    console.log("Searching for:", query);
    // এখানে API কল হবে
}

const debouncedSearch = debounce(handleSearch, 500); // 500ms delay

// Input field এ টাইপ করার সাথে সাথে debounce ফাংশন কাজ করবে
document.getElementById('searchInput').addEventListener('input', function(event) {
    debouncedSearch(event.target.value);
});

Here the debouncedSearch function will wait 500 milliseconds, then call the function, so that multiple key presses do not send multiple requests to the server.

How to use Debounce in React?

In React applications, the debounce function is usually used with the useEffect hook. Example:

import React, { useState, useEffect } from 'react';

function SearchComponent() {
    const [query, setQuery] = useState('');
    const [debouncedQuery, setDebouncedQuery] = useState(query);

    // useEffect to handle debounced query update
    useEffect(() => {
        const timer = setTimeout(() => {
            setDebouncedQuery(query);
        }, 500); // 500ms delay

        // Cleanup the timeout when query changes
        return () => {
            clearTimeout(timer);
        };
    }, [query]);

    useEffect(() => {
        if (debouncedQuery) {
            console.log("Searching for:", debouncedQuery);
            // এখানে API কল হবে
        }
    }, [debouncedQuery]);

    return (
        <input 
            type="text" 
            value={query}
            onChange={(e) => setQuery(e.target.value)} 
            placeholder="Search..."
        />
    );
}

export default SearchComponent;

In this example, the query state is updated as the user types. But the debouncedQuery state is only updated after 500 milliseconds, when the user stops typing. As a result API calls are made only when needed instead of multiple times.

Conclusion

The

Debounce technique is an effective way to improve performance in JavaScript and React. This is especially important for search engines, form validation and scroll events, where unnecessary multiple calls to events need to be avoided.

The above is the detailed content of Detailed discussion on using Debounce in JavaScript and React. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Custom Hooks in ReactNext article:Custom Hooks in React