Skip to main content
This is the React InstantSearch v7 documentation. If you’re upgrading from v6, see the upgrade guide. If you were using React InstantSearch Hooks, this v7 documentation applies—just check for necessary changes. To continue using v6, you can find the archived documentation.
React InstantSearch offers various APIs to let you customize your search and discovery experience without considering its inner workings. For example, you can customize how the experience looks: You can also adjust the data sent to or received from Algolia:

Highlight and snippet your search results

Search interfaces are all about helping users understand the results. When users perform a textual search, they need to know why they’re getting the search results they received. Algolia provides a typo-tolerant highlighting feature to display the matching parts in the results. Algolia also provides snippeting to create an excerpt of a longer piece of text, truncated to a fixed size around the match.
Snippeted attributes are also highlighted. When working with Snippet, the attribute must be set up in attributesToSnippet either inside the Algolia dashboard or at runtime.

On the web

React InstantSearch provides the Highlight and Snippet components to highlight and snippet your Algolia search results. Both widgets take two props:
  • attribute: the path to the highlighted attribute of the hit
  • hit: a single result object
React
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import {
  InstantSearch,
  Hits,
  Highlight,
  Snippet,
} from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');

function Hit({ hit }) {
  return (
    <article>
      <h1>
        <Highlight attribute="name" hit={hit} />
      </h1>
      <Snippet hit={hit} attribute="description" />
    </article>
  );
}

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

With React Native

The Highlight and Snippet components are designed for the web platform. To highlight matches in a React Native app, you can build a custom Highlight component using the provided getHighlightedParts and getPropertyByPath utilities from instantsearch.js.

Style your widgets

All React InstantSearch widgets use a set of conventional CSS classes compatible with the InstantSearch CSS themes. If you don’t want to use the themes, you can either write your own theme by following the existing classes and customizing the styles, or override the classes to pass yours instead.

Load the InstantSearch theme

React InstantSearch doesn’t inject any styles by default but comes with two optional themes: Algolia and Satellite. You can import them from a CDN or using npm.

From a CDN

The themes are available on jsDelivr. Unminified:
  • https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/reset.css
  • https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/algolia.css
  • https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite.css
Minified:
  • https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/reset-min.css
  • https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/algolia-min.css
  • https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite-min.css
The reset style sheet is included by default in the Satellite theme, so there’s no need to import it separately. Either copy the files into your own app or use a direct link to jsDelivr.
HTML
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/instantsearch.css@8.5.1/themes/satellite-min.css" integrity="sha256-woeV7a4SRDsjDc395qjBJ4+ZhDdFn8AqswN1rlTO64E=" crossorigin="anonymous">

Using npm

If your project imports CSS into JavaScript files using build tools (such as webpack, Parcel, Vite, or a framework that uses build tools (like or Nuxt), you can install the theme with npm.
npm install instantsearch.css
Then, you can import the theme directly into your app.
JavaScript
import 'instantsearch.css/themes/satellite.css';

Write your own theme

You can create your own theme based on the InstantSearch CSS classes. Either inspect the DOM with your developer tools and style accordingly or reuse an existing theme and customize it.
CSS
.ais-Breadcrumb-item--selected,
.ais-HierarchicalMenu-item--selected,
.ais-Menu-item--selected {
  font-weight: semibold;
}

/* ... */

Pass ustom CSS classes to widgets

If you’re using a class-based CSS framework like Bootstrap or Tailwind CSS, you can pass your own CSS classes to the classNames prop to style each element of the widgets.
React
// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <SearchBox
        classNames={{
          root: 'p-3 shadow-sm',
          form: 'relative',
          input: 'block w-full pl-9 pr-3 py-2 bg-white border border-slate-300 placeholder-slate-400 focus:outline-none focus:border-sky-500 focus:ring-sky-500 rounded-md focus:ring-1',
          submitIcon: 'absolute top-0 left-0 bottom-0 w-6',
        }}
      />
      {/* ... */}
    </InstantSearch>
  );
}
If you only want to pass classes to the root element, use the className React prop.
React
// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <SearchBox className="p-3 shadow-sm" />
      {/* ... */}
    </InstantSearch>
  );
}

Translate your widgets

You can customize every piece of static text in React InstantSearch widgets, such as “Load more” or “Show more” with the translations prop. This is useful if you want to change the text or work with a localized app. The translations prop is a key-value mapping. Each translation is either a string or a function that exposes some state. You can find the exact signature of the prop for each widget in their API reference.

With strings

Most translations expect string values.
React
// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <SearchBox
        translations={{
          submitButtonTitle: 'Envoyer',
        }}
      />
      {/* ... */}
    </InstantSearch>
  );
}

With functions

For dynamic values, translations expose a function.
React
// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      {/* ... */}
      <RefinementList
        attribute="categories"
        translations={{
          showMoreButtonText: ({ isShowingMore }) =>
            isShowingMore ? 'Voir moins' : 'Voir plus',
        }}
      />
    </InstantSearch>
  );
}

Change the list of items in widgets

Every widget and Hook that handles a list of items exposes a transformItems prop that lets you transform the items before displaying them in the UI. This is useful to sort or filter items. You can also use Hooks to add items that don’t come from Algolia, or append cached results to the list of displayed items.

Sort items

This example uses the transformItems prop to order the current refinements by ascending attribute:
React
// ...
import { orderBy } from 'lodash';

// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      {/* ... */}
      <CurrentRefinements
        transformItems={(items) => orderBy(items, 'attribute', 'asc')}
      />
    </InstantSearch>
  );
}
If you want to sort items in a RefinementList, use the sortBy prop.
React
// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      {/* ... */}
      <RefinementList
        attribute="categories"
        sortBy={['label:asc']}
      />
    </InstantSearch>
  );
}

Filter items

This example uses the transformItems prop to filter out items when the count is lower than 150.
React
// ...

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      {/* ... */}
      <RefinementList
        attribute="categories"
        transformItems={(items) => items.filter((item) => item.count >= 150)}
      />
    </InstantSearch>
  );
}

Display static values

The facet values exposed in widgets like RefinementList or Menu are dynamic, and update with the context of the search. However, sometimes you may want to display a static list that never changes. You can do so using transformItems. This example uses transformItems to display a static list of values. This RefinementList always and only displays the items “iPad” and “Printers”.
React
// ...
import { InstantSearch, RefinementList } from 'react-instantsearch-web';

// ...

const staticItems = [
  { label: 'Appliances', value: 'Appliances' },
  { label: 'Cell Phones', value: 'Cell Phones' },
];

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      {/* ... */}
      <RefinementList
        attribute="categories"
        transformItems={(items) => {
          return staticItems.map((staticItem) => ({
            ...staticItem,
            ...items.find((item) => item.value === staticItem.value),
          }));
        }}
      />
    </InstantSearch>
  );
}

Display facets without matches

Hiding facets when they don’t match a query can be counter-intuitive. However, because of how Algolia handles faceting, you have to rely on workarounds on the frontend to display facets with no hits. One way of displaying facets with no matches is to cache results the first time you receive them. Then, if the amount of actual facet hits that Algolia returns is below the limit set, you can append the cached facets to the list.
import React from 'react';
import { InstantSearch } from 'react-instantsearch';

import { CustomRefinementList } from './CustomRefinementList';
import { indexName, searchClient } from './searchClient';

function App() {
  return (
    <InstantSearch indexName={indexName} searchClient={searchClient}>
      <CustomRefinementList attribute="brand" />
    </InstantSearch>
  );
}
This solution comes with limitations:
  • Facet hits from a faceted search won’t work because Algolia only returns matching facets (the highlighting can’t apply to cached items).
  • You might need to sort again in the custom widget because the internal sorting happens before rendering.

Apply default values to widgets

When first loading the page, you might want to assign default values to some widgets. For example, you may want to set a default filter based on a user setting, pre-select an item in a RefinementList when you’re on a category page, or sync the UI with your URL state.

Providing an initial state

Providing an initial state is useful when you want to start from a given uiState but you expect it to change from user interactions with the widgets. This example provides an initialUiState to React InstantSearch.
React
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import {
  InstantSearch,
  Pagination,
  SearchBox,
} from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');
const indexName= 'instant_search';

function App() {
  return (
    <InstantSearch
      indexName={indexName}
      searchClient={searchClient}
      initialUiState={{
        [indexName]: {
          // Sets the initial search query for the SearchBox widget
          query: 'phone',
          // Sets the initial page number for the Pagination widget
          page: 5,
        },
      }}
    >
      <SearchBox />
      {/* ... */}
      <Pagination />
    </InstantSearch>
  );
}
Since initialUiState sets the initial state of your UI (widgets), you must also add the corresponding widgets to your implementation, or use virtual widgets.

Sync UI state and URL

Syncing your UI with the browser URL is a good practice. It lets users take one of your results pages, copy the URL, and share it. It also improves the user experience by enabling the use of the back and next browser buttons to keep track of previous searches. To sync the UI state and the URL, use the routing option.
React
import { InstantSearch, SearchBox } from 'react-instantsearch';
import { liteClient as algoliasearch } from 'algoliasearch/lite';

const searchClient = algoliasearch(ALGOLIA_APPLICATION_ID, ALGOLIA_SEARCH_API_KEY);

function App() {
  return (
    <InstantSearch
      searchClient={searchClient}
      indexName="instant_search"
      routing={true}
    >
      <SearchBox />
      {/* ... */}
    </InstantSearch>
  );
}
Note the presence of the SearchBox widget. When using routing, you must also add the corresponding widgets to your implementation.
To learn more, see Sync your URLs.

Manually set search parameters

Algolia supports a wide range of search parameters. If you want to use a search parameter that isn’t covered by any widget or Hook, use the Configure widget. Using Configure is also useful to provide a search parameter that users aren’t meant to interact with directly.
React
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch, Configure } from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <Configure
        analytics={false}
        distinct={true}
        getRankingInfo={true}
      />
    </InstantSearch>
  );
}

Filter results without using widgets or Hooks

If you need to set a fixed filter without letting users change it, pass filters to the Configure widget. This can be useful, for example, to reflect user preferences saved in your app.
React
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch, Configure } from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <Configure filters="free_shipping:true" />
    </InstantSearch>
  );
}
Don’t set filters on Configure for an attribute already managed by a widget, or they will conflict.

Dynamically update search parameters

The InstantSearch root component exposes an onStateChange prop. This function triggers whenever the UI state changes (such as typing in a search box or selecting a refinement). You get a chance to alter the next UI state or perform custom logic before applying it. In this example, there’s a static “All” item at the top of the categories refinement list. When checked, it clears all existing category refinements. This is achieved by intercepting the next UI state in onStateChange before it’s applied and changing it with custom logic.
React
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch, RefinementList } from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');

const indexName = 'instant_search';

export function App() {
  return (
    <InstantSearch
      indexName={indexName}
      searchClient={searchClient}
      onStateChange={({ uiState, setUiState }) => {
        const categories = uiState[indexName].refinementList?.categories || [];
        const [lastSelectedCategory] = categories.slice(-1);

        setUiState({
          ...uiState,
          [indexName]: {
            ...uiState[indexName],
            refinementList: {
              ...uiState[indexName].refinementList,
              categories: categories.filter((category) =>
                lastSelectedCategory === 'All' ? false : category !== 'All'
              ),
            },
          },
        });
      }}
    >
      <RefinementList
        attribute="categories"
        transformItems={(items) =>
          [
            {
              label: 'All',
              value: 'All',
              count: null,
              isRefined: items.every((item) => !item.isRefined),
            },
          ].concat(items)
        }
      />
      {/* ... */}
    </InstantSearch>
  );
}
If you’ve set a search parameter using Configure, you can update it like any React state.
React
import React, { useEffect, useState } from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch, Configure } from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');

const languages = [
  { label: 'Français', value: 'fr_FR' },
  { label: 'English', value: 'en_US' },
];

export function App() {
  const [language, setLanguage] = useState(languages[0].value);

  return (
    <>
      <label htmlFor="language">Language</label>
      <select
        id="language"
        value={language}
        onChange={(event) => setLanguage(event.target.value)}
      >
        {languages.map(({ label, value }) => (
          <option key={value} value={value}>
            {label}
          </option>
        ))}
      </select>
      <InstantSearch indexName={indexName} searchClient={searchClient}>
        <Configure filters={`language:${language}`} />
        {/* ... */}
      </InstantSearch>
    </>
  );
}

Customize the complete UI of the widgets

Hooks are the headless counterparts of widgets. They return APIs to build the UI as you see fit. If you feel limited by the provided customization options, you can use Hooks to control the render output. This is useful when using React InstantSearch together with a component library or when rendering to a non-DOM target like React Native. Hooks can also be helpful if you want to create a custom behavior or a radically different UI based on the APIs of an existing widget. For example, to set pre-determined search queries by clicking on a button, you could use useSearchBox and render a button that sets a given query on click.
React
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch, useSearchBox } from 'react-instantsearch';

const searchClient = algoliasearch('ALGOLIA_APPLICATION_ID', 'ALGOLIA_SEARCH_API_KEY');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <PopularQueries queries={['apple', 'samsung']} />
    </InstantSearch>
  );
}

function PopularQueries({ queries, ...props }) {
  const { refine } = useSearchBox(props);

  return (
    <div>
      {queries.map((query) => (
        <button key={query} onClick={() => refine(query)}>
          Look for "{query}"
        </button>
      ))}
    </div>
  );
}
Another example is when you need to create a virtual widget to apply a refinement without displaying anything on the page.

When not to use Hooks

When you need to customize the UI of a widget, you might be tempted to use Hooks. While this grants you complete control, it also means you become responsible for adequately implementing UI logic and accessibility. The provided UI components already handle this complexity and provide many customization options for you to change the way they look. If you only need to make visual changes to a widget, you should use customization options instead of reaching for Hooks. To summarize, avoid using Hooks to:

Custom components with Hooks

If you’re using a component library like Material UI or your own, you might want to use these components instead of the provided ones. You can use Hooks to access the necessary state and APIs to stitch React InstantSearch together with your custom components.
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch } from 'react-instantsearch';

import { CustomSortBy } from './CustomSortBy';

const searchClient = algoliasearch('undefined', 'undefined');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <CustomSortBy
        items={[
          { label: 'Featured', value: 'instant_search' },
          { label: 'Price (asc)', value: 'instant_search_price_asc' },
          { label: 'Price (desc)', value: 'instant_search_price_desc' },
        ]}
      />
    </InstantSearch>
  );
}
If you want to customize a widget, click its entry in the React InstantSearch API reference and then look up the Hook section on that page.

Build virtual widgets with Hooks

A virtual widget is an InstantSearch widget mounted in the app but which doesn’t render anything. Widgets do more than displaying a UI: they each interact with a piece of the UI state that maps to one or more Algolia search parameters. For example, the SearchBox controls the query, the RefinementList interacts with facetFilters, etc. When mounting a widget or using the corresponding Hook, it’s reflected in the InstantSearch UI state and included in search requests. For example, consider an ecommerce website where you want to have dedicated pages for your product categories. The categories are provided by your server, and passed to InstantSearch using initialUiState. The RefinementList widget doesn’t need to be displayed, but InstantSearch needs to be aware of its state. You can solve this by using a virtual widget.
import React from 'react';
import { useRefinementList } from 'react-instantsearch';

export function VirtualRefinementList(props) {
  useRefinementList(props);

  return null;
}
The virtual widget VirtualRefinementList refines results from Algolia according to the category retrieved from your server, like a hidden filter that’s always active.

Custom components without Hooks

If you’re using a component library like Material UI or your own, you might want to use these components instead of the provided ones. If your app uses class components instead of Hooks, you can manually create a Higher Order Component (HOC) from the hook and then use the HOC to access the necessary state and APIs to stitch React InstantSearch together with your custom components.
import React from 'react';
import { liteClient as algoliasearch } from 'algoliasearch/lite';
import { InstantSearch } from 'react-instantsearch';

import { CustomSortBy } from './CustomSortBy';

const searchClient = algoliasearch('undefined', 'undefined');

function App() {
  return (
    <InstantSearch indexName="instant_search" searchClient={searchClient}>
      <CustomSortBy
        items={[
          { label: 'Featured', value: 'instant_search' },
          { label: 'Price (asc)', value: 'instant_search_price_asc' },
          { label: 'Price (desc)', value: 'instant_search_price_desc' },
        ]}
      />
    </InstantSearch>
  );
}
If you want to customize a widget, click its entry in the React InstantSearch API reference and then look up the Hook section on that page.

Next steps

You now have a good starting point to create an even more custom experience with React InstantSearch. Next up, you could improve this app by:
I