API Reference / React InstantSearch Hooks / <InfiniteHits>
Signature
<InfiniteHits
  // Optional props
  hitComponent={React.JSXElementConstructor<{ hit: THit; sendEvent: SendEventForHits }>}
  showPrevious={boolean}
  transformItems={InfiniteHitsProps['transformItems']}
  cache={InfiniteHitsCache}
  classNames={Partial<InfiniteHitsClassNames>}
  ...props={React.ComponentProps<'div'>}
/>

About this widget

<InfiniteHits> is a widget that lets you display an infinite list of results.

Infinite hits are a list of results after which you can load more results without going to a next page.

You can also create your own UI with useInfiniteHits().

Examples

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from 'react';
import algoliasearch from 'algoliasearch/lite';
import { InstantSearch, InfiniteHits } from 'react-instantsearch-hooks-web';

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>
  );
}

Props

hitComponent
type: React.JSXElementConstructor<{ hit: THit; sendEvent: SendEventForHits }>
Required

A component that renders each hit from the results. It receives a hit and a sendEvent (for insights) prop.

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

1
<InfiniteHits hitComponent={({ hit }) => hit.objectID} />
showPrevious
type: boolean
default: true
Optional

Enable the button to load previous results.

1
2
3
4
<InfiniteHits
  // ...
  showPrevious={false}
/>
escapeHTML
type: boolean
default: true
Optional

Whether to escape HTML tags from hits string values.

1
2
3
4
<InfiniteHits
  // ...
  escapeHTML={false}
/>
transformItems
type: InfiniteHitsProps['transformItems']
Optional

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

In addition, the full results data is available, which includes all regular response parameters, as well as parameters from the helper (for example disjunctiveFacetsRefinements).

If you’re transforming an attribute you’re using with the <Highlight> widget, you also need to transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<InfiniteHits
  // ...
  transformItems={(items) => {
    return items.map(item => ({
      ...item,
      label: item.name.toUpperCase(),
    }));
  }}

  /* or, combined with results */
  transformItems={(items, { results }) => {
    return items.map((item, index) => ({
      ...item,
      position: { index, page: results.page },
    }));
  }}
/>
cache
type: InfiniteHitsCache
Optional

The Hook internally caches all loaded hits using its own internal in-memory cache implementation.

The library provides another implementation using 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.

1
2
3
4
5
6
7
8
import { createInfiniteHitsSessionStorageCache } from 'instantsearch.js/es/lib/infiniteHitsCache';

const sessionStorageCache = createInfiniteHitsSessionStorageCache();

<InfiniteHits
  // ...
  cache={sessionStorageCache}
/>
classNames
type: Partial<InfiniteHitsClassNames>
Optional

CSS classes to pass to the widget’s elements. This is useful to style widgets with class-based CSS frameworks like Bootstrap or Tailwind CSS.

  • root: The root element of the widget.
  • 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.
1
2
3
4
5
6
7
<InfiniteHits
  // ...
  classNames={{
    root: 'MyCustomInfiniteHits',
    list: 'MyCustomInfiniteHitsList MyCustomInfiniteHitsList--subclass',
  }}
/>
...props
type: React.ComponentProps<'div'>
Optional

Any <div> prop to forward to the root element of the widget.

1
2
3
4
5
<InfiniteHits
  // ...
  className="MyCustomInfiniteHits"
  title="My custom title"
/>

Hook

React InstantSearch Hooks 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 and returns APIs.

Usage

First, create your React component:

import { useInfiniteHits } from 'react-instantsearch-hooks-web';

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

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

Then, render the widget:

<CustomInfiniteHits {...props} />

Parameters

Hooks accept parameters. You can pass them manually, or forward the props from your custom component.

When you provide a function to Hooks, make sure to pass a stable reference with useCallback() to avoid rendering endlessly. Objects and arrays are memoized so you don’t have to stabilize them.

escapeHTML
type: boolean
default: true

Whether to escape HTML tags from hits string values.

1
2
3
const infiniteHitsApi = useInfiniteHits({
  escapeHTML: false,
});
transformItems
type: UseInfiniteHitsProps['transformItems']

Receives the items and is called before displaying them. Should return a new array with the same shape as the original array. Useful for transforming, removing, or reordering items.

In addition, the full results data is available, which includes all regular response parameters, as well as parameters from the helper (for example disjunctiveFacetsRefinements).

If you’re transforming an attribute you’re using with the <Highlight> widget, you also need to transform item._highlightResult[attribute].value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const infiniteHitsApi = useInfiniteHits({
  transformItems(items) {
    return items.map(item => ({
      ...item,
      label: item.name.toUpperCase(),
    }));
  },

  /* or, combined with results */
  transformItems(items, { results }) {
    return items.map((item, index) => ({
      ...item,
      position: { index, page: results.page },
    }));
  },
});
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, 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.

1
2
3
4
5
6
7
import { createInfiniteHitsSessionStorageCache } from 'instantsearch.js/es/lib/infiniteHitsCache';

const sessionStorageCache = createInfiniteHitsSessionStorageCache();

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

APIs

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

hits
type: THit[]

The matched hits returned from Algolia.

This returns the combined hits for all the pages that have been requested so far. You can leverage the highlighting feature of Algolia directly from the render function. Check the <Highlight> example for full implementation.

currentPageHits
type: THit[]

The matched hits from Algolia for the current page.

Unlike the hits 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 leverage the highlighting feature of Algolia directly from the render function. Check the <Highlight> example for full implementation.

results
type: SearchResults<THit>

The complete response from Algolia.

It contains the hits but also metadata about the page, number of hits, and more. Unless you need to access metadata, you should use hits instead.

isFirstPage
type: boolean

Whether the first page of hits has been reached.

isLastPage
type: boolean

Whether the last page of hits has been reached.

showPrevious
type: () => void

Loads the previous page of hits.

showMore
type: () => void

Loads the next page of hits.

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 middleware documentation to learn more.

Example

1
2
3
4
5
6
7
8
import React from 'react';
import { useInfiniteHits } from 'react-instantsearch-hooks-web';

function CustomInfiniteHits(props) {
  const { hits, isLastPage, showMore } = useInfiniteHits(props);

  return <>{/* Your JSX */}</>;
}
Did you find this page helpful?