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

# InfiniteHits

> Shows search results with a button to load more.

<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>

```tsx Signature theme={"system"}
<InfiniteHits
  // Optional props
  hitComponent={({ hit }) => JSX.Element}
  showPrevious={boolean}
  transformItems={function}
  cache={object}
  classNames={object}
  translations={object}
  ...props={ComponentProps<'div'>}
/>
```

## Import

```js JavaScript icon=code theme={"system"}
import { InfiniteHits } from "react-instantsearch";
```

<Card title="See this widget in action" icon="monitor-play" href="https://instantsearchjs.netlify.app/stories/?path=/story/results-infinitehits--default" horizontal>
  Preview this widget and its behavior.
</Card>

## About this widget

The `<InfiniteHits>` widget displays a list of results with a "Show more" button at the bottom of the list.
As an alternative to this approach,
[the infinite scroll guide](/doc/guides/building-search-ui/ui-and-ux-patterns/infinite-scroll/react)
describes how to create an automatically scrolling infinite hits experience.

See also: [Searches without results](/doc/guides/building-search-ui/going-further/conditional-display/react#handling-no-results)

<Tip>You can also create your own UI with [`useInfiniteHits`](#hook).</Tip>

## Examples

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React from "react";
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import { InstantSearch, InfiniteHits } from "react-instantsearch";

  const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

  function Hit({ hit }) {
    return JSON.stringify(hit);
  }

  function App() {
    return (
      <InstantSearch indexName="instant_search" searchClient={searchClient}>
        <InfiniteHits hitComponent={Hit} />
      </InstantSearch>
    );
  }
  ```

  ```tsx TypeScript theme={"system"}
  import React from "react";
  import { liteClient as algoliasearch } from "algoliasearch/lite";
  import { InstantSearch, InfiniteHits } from "react-instantsearch";
  import type { Hit as AlgoliaHit } from "instantsearch.js";

  const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

  type MyHit = AlgoliaHit<{
    name: string;
  }>;

  function Hit({ hit }: { hit: MyHit }) {
    return JSON.stringify(hit);
  }

  function App() {
    return (
      <InstantSearch indexName="instant_search" searchClient={searchClient}>
        <InfiniteHits<MyHit> hitComponent={Hit} />
      </InstantSearch>
    );
  }
  ```
</CodeGroup>

## Props

<ParamField body="hitComponent" type="(props: { hit: THit; sendEvent: SendEventForHits }) => JSX.Element" required>
  A component that renders each hit from the results.
  It receives a `hit` and a `sendEvent` (for [`insights`](/doc/api-reference/widgets/insights/react)) prop.

  When not provided, the widget displays the hit as a JSON string.

  ```jsx JavaScript icon=code theme={"system"}
  <InfiniteHits hitComponent={({ hit }) => hit.objectID} />;
  ```
</ParamField>

<ParamField body="bannerComponent" type="((props: { banner: SearchResults['renderingContent']['widgets']['banners'][0] }) => JSX.Element) | false">
  A component that renders the banner data on the `renderingContent` property from the Algolia response.
  It overrides the default banner rendering.

  When `false`, the widget does not render the banner.

  ```jsx JavaScript icon=code theme={"system"}
  // Override the default banner rendering
  <InfiniteHits
    // ...
    bannerComponent={({ banner }) => <img src={banner.image.urls[0].url} />}
  />
  // Disable the banner rendering
  <InfiniteHits
    // ...
    bannerComponent={false}
  />
  ```
</ParamField>

<ParamField body="showPrevious" type="boolean" default={true}>
  Enable the button to load previous results.

  ```jsx JavaScript icon=code theme={"system"}
  <InfiniteHits
    // ...
    showPrevious={false}
  />;
  ```
</ParamField>

<ParamField body="escapeHTML" type="boolean" default={true}>
  Whether to escape HTML tags from hits string values.

  ```jsx JavaScript icon=code theme={"system"}
  <InfiniteHits
    // ...
    escapeHTML={false}
  />;
  ```
</ParamField>

<ParamField body="transformItems" type="(items: object[], metadata: { results: SearchResults }) => object[]">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  If you transform an attribute you're using with the [`<Highlight>`](/doc/api-reference/widgets/highlight/react) widget,
  you must also transform the corresponding `item._highlightResult[attribute].value`.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    // Using only items
    const transformItems = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems = (items, { results }) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function Search() {
      return (
        <InfiniteHits
          // ...
          transformItems={transformItems}
        />
      );
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { InfiniteHitsProps } from "react-instantsearch";

    // Using only items
    const transformItems: InfiniteHitsProps["transformItems"] = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems: InfiniteHitsProps["transformItems"] = (
      items,
      { results },
    ) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function Search() {
      return (
        <InfiniteHits
          // ...
          transformItems={transformItems}
        />
      );
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="cache" type="InfiniteHitsCache">
  The widget caches all loaded hits.
  By default, it uses its own internal in-memory cache implementation.
  Alternatively, use [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage)
  to retain the cache even if users reload the page.

  You can also implement your own cache object with `read` and `write` methods.
  This can be handy if you need to persist the data across sessions
  or if you expect the cached data to grow larger than the browser's
  [5 MB allowed storage](https://developer.mozilla.org/en-US/docs/Web/API/Storage_API/Storage_quotas_and_eviction_criteria#web_storage).

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    import { createInfiniteHitsSessionStorageCache } from "instantsearch.js/es/lib/infiniteHitsCache";

    const sessionStorageCache = createInfiniteHitsSessionStorageCache();

    <InfiniteHits
      // ...
      cache={sessionStorageCache}
    />;
    ```

    ```ts InfinitsHitsCache theme={"system"}
    type InfiniteHitsCache = {
      read: ({
        state,
      }: {
        state: PlainSearchParameters;
      }) => InfiniteHitsCachedHits | null;
      write: ({
        state,
        hits,
      }: {
        state: PlainSearchParameters;
        hits: InfiniteHitsCachedHits;
      }) => void;
    };

    type InfiniteHitsCachedHits = {
      [page: number]: Hits;
    };
    ```
  </CodeGroup>
</ParamField>

<ParamField body="classNames" type="Partial<InfiniteHitsClassNames>">
  The [CSS classes you can override](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/react#style-your-widgets) and pass to the widget's elements.
  It's useful to style widgets with class-based CSS frameworks like [Bootstrap](https://getbootstrap.com) or [Tailwind CSS](https://tailwindcss.com).

  * `root`. The widget's root element.
  * `emptyRoot`. The root element without results.
  * `list`. The list of results.
  * `item`. The list items.
  * `loadPrevious`. The "Load previous" button.
  * `disabledLoadPrevious`. The "Load previous" button when there are no previous results to load.
  * `loadMore`. The "Load more" button.
  * `disabledLoadMore`. The "Load more" button when there are no more results to load.
  * `bannerRoot`. The root element of the banner.
  * `bannerImage`. The image element of the banner.
  * `bannerLink`. The anchor element of the banner.

  ```jsx JavaScript icon=code theme={"system"}
  <InfiniteHits
    // ...
    classNames={{
      root: "MyCustomInfiniteHits",
      list: "MyCustomInfiniteHitsList MyCustomInfiniteHitsList--subclass",
    }}
  />;
  ```
</ParamField>

<ParamField body="translations" type="Partial<InfiniteHitsTranslations>">
  A dictionary of translations to customize the UI text and support internationalization.

  * `showPreviousButtonText`. The text for the "Show previous" button.
  * `showMoreButtonText`. The text for the "Show more" button.

  ```jsx JavaScript icon=code theme={"system"}
  <InfiniteHits
    // ...
    translations={{
      showPreviousButtonText: "Load previous results",
      showMoreButtonText: "Load more results",
    }}
  />;
  ```
</ParamField>

<ParamField body="...props" type="React.ComponentProps<'div'>">
  Any `<div>` prop to forward to the widget's root element.

  ```jsx JavaScript icon=code theme={"system"}
  <InfiniteHits
    // ...
    className="MyCustomInfiniteHits"
    title="My custom title"
  />;
  ```
</ParamField>

## Hook

React InstantSearch let you create your own UI for the `<InfiniteHits>` widget with `useInfiniteHits`.
Hooks provide APIs to access the widget state and interact with InstantSearch.

The `useInfiniteHits` Hook accepts [parameters](#parameters) and returns [APIs](#hook).
It must be used inside the [`<InstantSearch>`](/doc/api-reference/widgets/instantsearch/react) component.

### Usage

First, create your React component:

```jsx JavaScript icon=code theme={"system"}
import { useInfiniteHits } from "react-instantsearch";

function CustomInfiniteHits(props) {
  const {
    items,
    currentPageHits,
    results,
    banner,
    isFirstPage,
    isLastPage,
    showPrevious,
    showMore,
    sendEvent,
  } = useInfiniteHits(props);

  return <>{/*Your JSX*/}</>;
}
```

Then, render the widget:

```jsx JavaScript icon=code theme={"system"}
<CustomInfiniteHits {...props} />;
```

### Parameters

Hooks accept parameters. You can either pass them manually or forward props from a custom component.

<Note>
  When passing functions to Hooks, ensure stable references to prevent unnecessary re-renders.
  Use [`useCallback()`](https://reactjs.org/docs/hooks-reference.html#usecallback) for memoization.
  Arrays and objects are automatically memoized.
</Note>

<ParamField body="escapeHTML" type="boolean" default={true}>
  Whether to escape HTML tags from hits string values.

  ```jsx JavaScript icon=code theme={"system"}
  const infiniteHitsApi = useInfiniteHits({
    escapeHTML: false,
  });
  ```
</ParamField>

<ParamField body="transformItems" type="(items: object[], metadata: { results: SearchResults }) => object[]">
  A function that receives the list of items before they are displayed.
  It should return a new array with the same structure.
  Use this to transform, filter, or reorder the items.

  The function also has access to the full `results` data,
  including all standard [response parameters](/doc/guides/building-search-ui/going-further/backend-search/in-depth/understanding-the-api-response/)
  and [parameters from the helper](https://community.algolia.com/algoliasearch-helper-js/reference.html#query-parameters),
  such as `disjunctiveFacetsRefinements`.

  If you transform an attribute you're using with the [`<Highlight>`](/doc/api-reference/widgets/highlight/react) widget,
  you must also transform the corresponding `item._highlightResult[attribute].value`.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    // Using only items
    const transformItems = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems = (items, { results }) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function InfiniteHits() {
      const infiniteHitsApi = useInfiniteHits({
        // ...
        transformItems,
      });

      return <>{/* Your JSX */}</>;
    }
    ```

    ```tsx TypeScript theme={"system"}
    import type { UseInfiniteHitsProps } from "react-instantsearch";

    // Using only items
    const transformItems: UseInfiniteHitsProps["transformItems"] = (items) => {
      return items.map((item) => ({
        ...item,
        label: item.name.toUpperCase(),
      }));
    };

    // Using items and results
    const transformItems: UseInfiniteHitsProps["transformItems"] = (
      items,
      { results },
    ) => {
      return items.map((item, index) => ({
        ...item,
        position: { index, page: results.page },
      }));
    };

    function InfiniteHits() {
      const infiniteHitsApi = useInfiniteHits({
        // ...
        transformItems,
      });

      return <>{/* Your JSX */}</>;
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="cache" type="InfiniteHitsCache">
  The Hook internally caches all loaded hits using its own internal in-memory cache implementation.

  The library provides another implementation using [`sessionStorage`](https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage), which is more persistent and lets you restore the scroll position when you leave and come back to the search page.

  You can also provide your own implementation by providing a cache object with `read` and `write` methods.

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    import { createInfiniteHitsSessionStorageCache } from "instantsearch.js/es/lib/infiniteHitsCache";

    const sessionStorageCache = createInfiniteHitsSessionStorageCache();

    const infiniteHitsApi = useInfiniteHits({
      cache: sessionStorageCache,
    });
    ```

    ```ts TypeScript theme={"system"}
    type InfiniteHitsCache = {
      read: ({
        state,
      }: {
        state: PlainSearchParameters;
      }) => InfiniteHitsCachedHits | null;
      write: ({
        state,
        hits,
      }: {
        state: PlainSearchParameters;
        hits: InfiniteHitsCachedHits;
      }) => void;
    };

    type InfiniteHitsCachedHits = {
      [page: number]: Hits;
    };
    ```
  </CodeGroup>
</ParamField>

### APIs

Hooks return APIs, such as state and functions.
You can use them to build your UI and interact with React InstantSearch.

<ResponseField name="items" type="THit[]">
  The matched hits returned from Algolia.

  This returns the combined hits for all the pages that have been requested so far.
  Use [Algolia's highlighting feature](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#highlight-and-snippet-your-search-results)
  directly from the render function.
</ResponseField>

<ResponseField name="currentPageHits" type="THit[]">
  The matched hits from Algolia for the current page.

  Unlike the [`items`](#param-items) parameter, this only returns the hits for the requested page.
  This can be useful if you want to customize how to add the new page of hits to the existing list.

  You can use [Algolia's highlighting feature](/doc/guides/building-search-ui/widgets/customize-an-existing-widget/js#highlight-and-snippet-your-search-results) directly from the render function.
</ResponseField>

<ResponseField name="results" type="SearchResults<THit>">
  The complete response from Algolia.

  It contains the `hits`, metadata about the page, the number of hits, and more.
  Unless you need to access metadata, use [`items`](#param-items) instead.
</ResponseField>

<ResponseField name="banner" type="SearchResults['renderingContent']['widgets']['banners'][0]">
  The banner data from the `renderingContent` property in the Algolia response.
</ResponseField>

<ResponseField name="isFirstPage" type="boolean">
  Whether the first page of hits has been reached.
</ResponseField>

<ResponseField name="isLastPage" type="boolean">
  Whether the last page of hits has been reached.
</ResponseField>

<ResponseField name="showPrevious" type="() => void">
  Loads the previous page of hits.
</ResponseField>

<ResponseField name="showMore" type="() => void">
  Loads the next page of hits.
</ResponseField>

<ResponseField name="sendEvent" type="(eventType: string, hits: Hit  |  Hits, eventName?: string) => void">
  The function to send `click` or `conversion` events.

  The `view` event is automatically sent when this hook renders hits.
  Check the [`insights`](/doc/api-reference/widgets/insights/react) documentation to learn more.
</ResponseField>

### Example

<CodeGroup>
  ```jsx JavaScript theme={"system"}
  import React from "react";
  import { useInfiniteHits } from "react-instantsearch";

  function CustomInfiniteHits(props) {
    const { items, sendEvent, showPrevious, showMore, isFirstPage, isLastPage } =
      useInfiniteHits(props);

    return (
      <div>
        <button onClick={showPrevious} disabled={isFirstPage}>
          Show previous results
        </button>
        <ol>
          {items.map((hit) => (
            <li
              key={hit.objectID}
              onClick={() => sendEvent("click", hit, "Hit Clicked")}
              onAuxClick={() => sendEvent("click", hit, "Hit Clicked")}
            >
              <div style={{ wordBreak: "break-all" }}>
                {JSON.stringify(hit).slice(0, 100)}…
              </div>
            </li>
          ))}
        </ol>
        <button onClick={showMore} disabled={isLastPage}>
          Show more results
        </button>
      </div>
    );
  }
  ```

  ```tsx TypeScript theme={"system"}
  import React from "react";
  import { useInfiniteHits, UseInfiniteHitsProps } from "react-instantsearch";

  function CustomInfiniteHits(props: UseInfiniteHitsProps) {
    const { items, sendEvent, showPrevious, showMore, isFirstPage, isLastPage } =
      useInfiniteHits(props);

    return (
      <div>
        <button onClick={showPrevious} disabled={isFirstPage}>
          Show previous results
        </button>
        <ol>
          {items.map((hit) => (
            <li
              key={hit.objectID}
              onClick={() => sendEvent("click", hit, "Hit Clicked")}
              onAuxClick={() => sendEvent("click", hit, "Hit Clicked")}
            >
              <div style={{ wordBreak: "break-all" }}>
                {JSON.stringify(hit).slice(0, 100)}…
              </div>
            </li>
          ))}
        </ol>
        <button onClick={showMore} disabled={isLastPage}>
          Show more results
        </button>
      </div>
    );
  }
  ```
</CodeGroup>

## Click and conversion events

If the [`insights`](/doc/api-reference/widgets/instantsearch/react#param-insights) option is `true`,
the `InfiniteHits` component automatically sends a `click` event with the following "shape" to the Insights API whenever users click a hit.

```json JSON icon=braces theme={"system"}
{
  "eventType": "click",
  "insightsMethod": "clickedObjectIDsAfterSearch",
  "payload": {
    "eventName": "Hit Clicked"
    // …
  },
  "widgetType": "ais.infiniteHits"
}
```

To customize this event,
use the `sendEvent` function in your [`hitComponent`](#param-hit-component) and send a custom `click` event.

```jsx JavaScript icon=code theme={"system"}
<InfiniteHits
  hitComponent={({ hit, sendEvent }) => (
    <div onClick={() => sendEvent("click", hit, "Product Clicked")}>
      <h2>
        <Highlight attributeName="name" hit={hit} />
      </h2>
      <p>{hit.description}</p>
    </div>
  )}
/>;
```

The `sendEvent` function also accepts an object as a fourth argument to send directly to the Insights API.
You can use it, for example, to send special `conversion` events with a subtype.

```jsx JavaScript icon=code theme={"system"}
<InfiniteHits
  hitComponent={({ hit, sendEvent }) => (
    <div>
      <h2>
        <Highlight attributeName="name" hit={hit} />
      </h2>
      <p>{hit.description}</p>
      <button
        onClick={() =>
          sendEvent("conversion", hit, "Added To Cart", {
            // Special subtype
            eventSubtype: "addToCart",
            // An array of objects representing each item added to the cart
            objectData: [
              {
                // The discount value for this item, if applicable
                discount: hit.discount || 0,
                // The price value for this item (minus the discount)
                price: hit.price,
                // How many of this item were added
                quantity: 2,
              },
            ],
            // The total value of all items
            value: hit.price * 2,
            // The currency code
            currency: "USD",
          })
        }
      >
        Add to cart
      </button>
    </div>
  )}
/>;
```

<Note>
  Use strings to represent monetary values in major currency units (for example, '5.45').
  This avoids floating-point rounding issues, especially when performing calculations.
</Note>

See also: [Send click and conversion events with React InstantSearch](/doc/guides/building-search-ui/events/react)
