Implementing an Autocomplete Search Box Using React Query and Algolia

Provide a code example for creating a dynamic autocomplete search component using React Query for data management and Algolia for search capabilities.
import { useQuery } from 'react-query';
import algoliasearch from 'algoliasearch/lite';
import { useState } from 'react';
Import necessary libraries and hooks. React Query for fetching data, Algoliasearch for searching, and useState for managing the search query state.
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
const index = searchClient.initIndex('YourIndexName');
Initialize Algolia search client with your application ID and search-only API key, and specify the index you want to search within.
function useAlgoliaQuery(query) {
  return useQuery(['algoliaSearch', query], () =>, {
    enabled: !!query,
    keepPreviousData: true
Define a custom hook using React Query to fetch search results from Algolia. The search is only triggered if the query is not empty.
function AutocompleteSearchBox() {
  const [query, setQuery] = useState('');
  const { data, isFetching } = useAlgoliaQuery(query);

  return (
        onChange={(e) => setQuery(}
      {isFetching && <div>Loading...</div>}
        {data? => (
          <li key={hit.objectID}>{}</li>
Create the AutocompleteSearchBox component that utilizes the useAlgoliaQuery hook to fetch and display search results. Includes an input for the query and displays results in a list.