Filtering and Faceting Search Results with React Query and Algolia

Illustrate how to implement filtering and faceting in a search interface, using React Query for state management and Algolia for the search logic, enhancing user search experiences.
import { useQuery } from 'react-query';
import algoliasearch from 'algoliasearch/lite';

// Initialize Algolia search client
const searchClient = algoliasearch('YourApplicationID', 'YourSearchOnlyAPIKey');
const algoliaIndex = searchClient.initIndex('your_index_name');
This code snippet initializes the Algolia search client with your application ID and search-only API key. It also specifies the index you'll be querying.
const fetchAlgoliaResults = async ({ queryKey }) => {
  const [_key, { query, facetFilters }] = queryKey;
  const { hits } = await, { facetFilters });
  return hits;
Defines an asynchronous function to fetch search results from Algolia. It accepts a queryKey from react-query which includes the search query and any facetFilters for filtering results.
const useAlgoliaSearch = (query, facetFilters) => {
  return useQuery(['algoliaSearch', { query, facetFilters }], fetchAlgoliaResults);
This custom hook uses react-query's useQuery to fetch and cache search results from Algolia based on the user's search input and selected facet filters.
const SearchResults = ({ query, facetFilters }) => {
  const { data: hits, isError, isLoading } = useAlgoliaSearch(query, facetFilters);

  if (isLoading) return <div>Loading...</div>;
  if (isError) return <div>Error fetching results.</div>;

  return (
      { => (
        <li key={hit.objectID}>{}</li>
A component that displays the search results. It uses the useAlgoliaSearch hook to fetch results based on the current query and selected facet filters. It handles loading and error states, and renders a list of hits.
const FacetFilter = ({ attribute, onSelectFilter }) => {
  // Example facet values could be hard-coded or fetched from Algolia
  const facets = ['Brand A', 'Brand B', 'Brand C'];

  return (
      { => (
        <button key={facet} onClick={() => onSelectFilter(`${attribute}:${facet}`)}>
This component renders buttons for each facet filter value. When a button is clicked, it calls onSelectFilter with the filter to apply. In a real application, facets could be fetched dynamically from Algolia.