Blog>
Snippets

Optimizing React Query Requests with Debouncing in Algolia Searches

Demonstrate the implementation of a debouncing mechanism to optimize search queries sent to Algolia when using the React Query library, improving performance and user experience.
function debounce(fn, delay) {
  let timeoutID = null;
  return function (...args) {
    clearTimeout(timeoutID);
    timeoutID = setTimeout(() => {
      fn(...args);
    }, delay);
  };
}
Defines a debounce function that delays the execution of the function it wraps until after a specified delay has passed since the last time it was invoked.
import { useQuery } from 'react-query';
import algoliasearch from 'algoliasearch/lite';

const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
const index = searchClient.initIndex('your_index_name');
Sets up React Query and Algolia, initializing the Algolia search client with your application ID and search-only API key, and specifying the index to search against.
function useDebouncedSearch(query, delay) {
  const debouncedSearch = React.useMemo(() => debounce((currentQuery) => {
    return index.search(currentQuery);
  }, delay), [delay]);

  return useQuery(['algoliaSearch', query], () => debouncedSearch(query), {
    enabled: !!query,
  });
}
A custom hook that uses useMemo to create a memoized version of a debounced search function, which is then used in a React Query useQuery call to fetch data from Algolia. The query is only enabled if there is a query to search.