> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Conditional display

> Learn how to improve your React InstantSearch app when there are no results, when there's no query, or when there are errors.

export const SearchQuery = () => <Tooltip tip="The text users enter into a search box. In the Search API, this corresponds to the query parameter. A search query is often used with filters, facets, and other parameters, but these aren't part of the query text itself.">
    search query
  </Tooltip>;

export const Filter = () => <Tooltip tip="A filter is a condition that limits which records Algolia returns. Filters often use one or more facet-value pairs, such as brand:Apple AND color:red. You can also filter by numeric values, dates, tags, booleans, or geographic constraints." cta="Filtering" href="/doc/guides/managing-results/refine-results/faceting">
    filter
  </Tooltip>;

<div className="not-prose algolia-flavor-switcher">
  <div className="afs-dropdown">
    <div className="afs-trigger" role="button" tabIndex="0" aria-haspopup="listbox">
      <span className="afs-current">React</span>

      <svg className="afs-chevron lucide lucide-chevron-down" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
        <path d="m6 9 6 6 6-6" />
      </svg>
    </div>

    <ul className="afs-menu" role="listbox">
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/guides/building-search-ui/going-further/conditional-display/js"><span className="afs-option-name">JavaScript</span><span className="afs-option-lib">InstantSearch.js</span></a></li>
      <li role="option" aria-selected="true"><a className="afs-option is-current" href="/doc/guides/building-search-ui/going-further/conditional-display/react"><span className="afs-option-name">React</span><span className="afs-option-lib">React InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/guides/building-search-ui/going-further/conditional-display/vue"><span className="afs-option-name">Vue</span><span className="afs-option-lib">Vue InstantSearch</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/guides/building-search-ui/going-further/conditional-display/ios"><span className="afs-option-name">iOS</span><span className="afs-option-lib">InstantSearch iOS</span></a></li>
      <li role="option" aria-selected="false"><a className="afs-option" href="/doc/guides/building-search-ui/going-further/conditional-display/android"><span className="afs-option-name">Android</span><span className="afs-option-lib">InstantSearch Android</span></a></li>
    </ul>
  </div>
</div>

<Note>
  This is the **React InstantSearch v7** documentation.
  If you're upgrading from v6, see the [upgrade guide](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-v6-to-react-instantsearch-v7).
  If you were using React InstantSearch Hooks,
  this v7 documentation applies—just check for [necessary changes](/doc/guides/building-search-ui/upgrade-guides/react/#migrate-from-react-instantsearch-hooks-to-react-instantsearch-v7).
  To continue using v6, you can find the [archived documentation](https://algolia.com/old-docs/deprecated/instantsearch/react/v6/api-reference/instantsearch/).
</Note>

This guide describes what to do when there are [no results](#handling-no-results),
when there's [no query](#handling-empty-queries),
or when there are [errors](#handling-errors).
**Sometimes, though, users may not get any hits if their device [can't access the network or the network connection is slow](/doc/guides/building-search-ui/ui-and-ux-patterns/pagination/react#no-hits-or-is-the-search-still-in-progress).**

If you want to feature content in your search results based on a set of conditions, you can use Algolia Rules:

* [Feature specific data from within your records](https://www.algolia.com/ecommerce-merchandising-playbook/merchandise-search-results-page/) to, for example, show promotional prices during a sales period
* [Display advertisements or promotional banners](/doc/guides/managing-results/rules/merchandising-and-promoting/how-to/add-banners).

<Info>
  To learn how to suppress InstantSearch's initial <SearchQuery />,
  see [Conditional requests](/doc/guides/building-search-ui/going-further/conditional-requests/react).
</Info>

## Handling no results

Since not all queries lead to results, it's essential to let users know when this happens by **providing hints on how to adjust the query.**

### Display a message

The easiest way to display a fallback message when a query doesn't return results is to use the [`useInstantSearch()`](/doc/api-reference/widgets/use-instantsearch/react) Hook to create a wrapper component:

```jsx React icon=code theme={"system"}
function App(props) {
  return (
    <InstantSearch {...props}>
      <SearchBox />
      <NoResultsBoundary fallback={<NoResults />}>
        <Hits />
      </NoResultsBoundary>
    </InstantSearch>
  );
}

function NoResultsBoundary({ children, fallback }) {
  const { results } = useInstantSearch();

  // The `__isArtificial` flag makes sure not to display the No Results message
  // when no hits have been returned.
  if (!results.__isArtificial && results.nbHits === 0) {
    return (
      <>
        {fallback}
        <div hidden>{children}</div>
      </>
    );
  }

  return children;
}

function NoResults() {
  const { indexUiState } = useInstantSearch();

  return (
    <div>
      <p>
        No results for <q>{indexUiState.query}</q>.
      </p>
    </div>
  );
}
```

You can pass anything to display results, including [`<InfiniteHits>`](/doc/api-reference/widgets/infinite-hits/react) or a custom component that uses the [`useHits()`](/doc/api-reference/widgets/hits/react#hook) Hook.

<Info>
  To prevent undesirable, additional search requests,
  see [Show and hide widgets](/doc/guides/building-search-ui/widgets/show-and-hide-widgets/react).
</Info>

### Let users reset filters and facets

If users apply an overly specific <Filter /> configuration, they may not find any results.
You should account for this by letting them reset filters from the "no results" display so they can start another search.

Do this with the [`<ClearRefinements>`](/doc/api-reference/widgets/clear-refinements/react) widget.

```jsx React icon=code theme={"system"}
function NoResults() {
  const { indexUiState } = useInstantSearch();

  return (
    <div>
      <p>
        No results for <q>{indexUiState.query}</q>.
      </p>
      <ClearRefinements excludedAttributes={[]} />
    </div>
  );
}
```

## Handling empty queries

By default, InstantSearch always shows you results, even when the query is empty.
Depending on your use case and how you build your UI,
you may only want to show results when there's a query.

```jsx React icon=code theme={"system"}
function App(props) {
  return (
    <InstantSearch {...props}>
      <SearchBox />
      <EmptyQueryBoundary fallback={null}>
        <Hits />
      </EmptyQueryBoundary>
    </InstantSearch>
  );
}

function EmptyQueryBoundary({ children, fallback }) {
  const { indexUiState } = useInstantSearch();

  if (!indexUiState.query) {
    return (
      <>
        {fallback}
        <div hidden>{children}</div>
      </>
    );
  }

  return children;
}
```

<Info>
  Follow best practices for [showing and hiding React InstantSearch widgets](/doc/guides/building-search-ui/widgets/show-and-hide-widgets/react) to prevent undesirable additional search requests.
</Info>

## Handling errors

When an error occurs, you can display a specific piece of content to help users return to the standard state.

```jsx React icon=code theme={"system"}
import React, { useEffect, useState } from "react";
import * as Toast from "@radix-ui/react-toast";
import { useInstantSearch } from "react-instantsearch";

function SearchErrorToast() {
  const { addMiddlewares } = useInstantSearch();
  const [error, setError] = useState(null);

  useEffect(() => {
    const middleware = ({ instantSearchInstance }) => {
      function handleError(searchError) {
        setError(searchError);
      }

      return {
        subscribe() {
          instantSearchInstance.addListener("error", handleError);
        },
        unsubscribe() {
          instantSearchInstance.removeListener("error", handleError);
        },
      };
    };

    return addMiddlewares(middleware);
  }, [addMiddlewares]);

  if (!error) {
    return null;
  }

  return (
    <Toast.Provider>
      <Toast.Root
        onOpenChange={(isOpen) => {
          if (!isOpen) {
            setError(null);
          }
        }}
      >
        <Toast.Title>{error.name}</Toast.Title>
        <Toast.Description>{error.message}</Toast.Description>
      </Toast.Root>

      <Toast.Viewport />
    </Toast.Provider>
  );
}

function App(props) {
  return (
    <InstantSearch {...props}>
      <SearchErrorToast />
      <SearchBox />
      <Hits />
    </InstantSearch>
  );
}
```
