useSearchState | Yext Hitchhikers Platform

useSearchState reads a value from the SearchHeadless instance and subscribes to updates. It’s used by all the components in the Search UI React library and you can also use it to build custom components.

useSearchState MUST be used in a component that is wrapped in a SearchHeadlessProvider .

Basic Example

Here’s a simple example that uses useSearchState that renders the most recent search query:

import { useSearchState } from '@yext/search-headless-react';

export default function MostRecentSearch() {
  const mostRecentSearch = useSearchState(state => state.query.mostRecentSearch);
  return <div>Showing results for {mostRecentSearch}</div>;
}

You can see all the possible fields stored in state in the Github documentation .

Extending Search UI Component Functionality

useSearchState can be used to extend or override the functionality of some of the Search UI components.

In this example, a component that says “loading” is rendered until a search is complete:

import { useSearchState } from "@yext/search-headless-react";
import {
  SearchBar,
  StandardCard,
  VerticalResults,
} from "@yext/search-ui-react";

const SearchComponent = () => {
  const loading = useSearchState((state) => state.searchStatus.isLoading);

  return (
    <div className="flex justify-center px-4 py-6">
      <div className="w-full max-w-5xl">
        <SearchBar />
        {loading ? (
          <div>Loading...</div>
        ) : (
          <VerticalResults CardComponent={StandardCard} />
        )}
      </div>
    </div>
  );
}

export default App;

Creating Custom UI Components

You can use the useSearchState hook (often in combination with the useSearchActions hook) to create your own Search UI components. The Building a Custom Facet Component guide walks you through how to build your own facet component with hooks.

API Reference

You can subscribe to any part of the SearchHeadless state with the useSearchState hook. To see what State looks like, check out this Github documentation .