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.
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.
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); }; }
does the following:
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.
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.
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!