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

# InstantSearch

> Root component for React InstantSearch apps.

export const Facet = () => <Tooltip tip="An attribute in your records that lets users filter or group results (for example, by color, brand, or price)." cta="Faceting" href="/doc/guides/managing-results/refine-results/faceting">
    facet
  </Tooltip>;

export const FlavorSwitcher = ({current, baseHref = "", options = [], label = "InstantSearch framework"}) => {
  if (options.length === 0) {
    return <div className="not-prose" role="alert" style={{
      margin: "0.25rem 0 1.5rem",
      padding: "0.75rem",
      border: "1px solid #f59e0b",
      borderRadius: "0.625rem",
      color: "inherit",
      fontSize: "0.875rem"
    }}>
        FlavorSwitcher requires at least one option.
      </div>;
  }
  const selected = options.find(option => option.value === current) ?? options[0];
  return <div className="not-prose mint-flavor-switcher">
      <style>{`
        .mint-flavor-switcher {
          --mfs-bg: #ffffff;
          --mfs-bg-hover: #f4f4f5;
          --mfs-bg-current: #eef2ff;
          --mfs-border: #d4d4d8;
          --mfs-fg: #18181b;
          --mfs-muted: #71717a;
          --mfs-accent: #4f46e5;
          position: relative;
          width: min(100%, 19rem);
          margin: 0.25rem 0 1.5rem;
          color: var(--mfs-fg);
          font-size: 0.875rem;
          line-height: 1.25rem;
        }

        .dark .mint-flavor-switcher {
          --mfs-bg: #18181b;
          --mfs-bg-hover: #27272a;
          --mfs-bg-current: #272747;
          --mfs-border: #3f3f46;
          --mfs-fg: #fafafa;
          --mfs-muted: #a1a1aa;
          --mfs-accent: #a5b4fc;
        }

        .mint-flavor-switcher details {
          position: relative;
        }

        .mint-flavor-switcher summary {
          display: flex;
          min-height: 2.75rem;
          box-sizing: border-box;
          align-items: center;
          justify-content: space-between;
          gap: 0.75rem;
          padding: 0.625rem 0.75rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          color: var(--mfs-fg);
          cursor: pointer;
          font-weight: 600;
          list-style: none;
          transition: border-color 150ms ease, box-shadow 150ms ease;
        }

        .mint-flavor-switcher summary::-webkit-details-marker {
          display: none;
        }

        .mint-flavor-switcher summary:hover {
          border-color: var(--mfs-accent);
        }

        .mint-flavor-switcher summary:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: 2px;
        }

        .mint-flavor-switcher__label {
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .mint-flavor-switcher__chevron {
          flex: none;
          transition: transform 150ms ease;
        }

        .mint-flavor-switcher details[open] .mint-flavor-switcher__chevron {
          transform: rotate(180deg);
        }

        .mint-flavor-switcher__menu {
          position: absolute;
          z-index: 50;
          top: calc(100% + 0.375rem);
          left: 0;
          width: 100%;
          box-sizing: border-box;
          margin: 0;
          padding: 0.375rem;
          border: 1px solid var(--mfs-border);
          border-radius: 0.625rem;
          background: var(--mfs-bg);
          box-shadow: 0 12px 30px rgb(0 0 0 / 16%);
          list-style: none;
        }

        .mint-flavor-switcher__menu li {
          margin: 0;
          padding: 0;
        }

        .mint-flavor-switcher__option {
          display: grid;
          gap: 0.125rem;
          padding: 0.625rem 0.75rem;
          border-radius: 0.4rem;
          color: var(--mfs-fg);
          text-decoration: none;
        }

        .mint-flavor-switcher__option:hover {
          background: var(--mfs-bg-hover);
        }

        .mint-flavor-switcher__option:focus-visible {
          outline: 2px solid var(--mfs-accent);
          outline-offset: -2px;
        }

        .mint-flavor-switcher__option[aria-current="page"] {
          background: var(--mfs-bg-current);
          color: var(--mfs-accent);
        }

        .mint-flavor-switcher__name {
          font-weight: 600;
        }

        .mint-flavor-switcher__description {
          color: var(--mfs-muted);
          font-size: 0.8125rem;
        }

        @media (prefers-reduced-motion: reduce) {
          .mint-flavor-switcher summary,
          .mint-flavor-switcher__chevron {
            transition: none;
          }
        }
      `}</style>

      <details>
        <summary aria-label={`${label}: ${selected.label}`}>
          <span className="mint-flavor-switcher__label">{selected.label}</span>
          <svg className="mint-flavor-switcher__chevron" width="18" height="18" 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>
        </summary>

        <ul className="mint-flavor-switcher__menu" aria-label={label}>
          {options.map(option => {
    const isCurrent = option.value === selected.value;
    const href = option.href ?? `${baseHref.replace(/\/$/, "")}/${encodeURIComponent(option.value)}`;
    return <li key={option.value}>
                <a className="mint-flavor-switcher__option" href={href} aria-current={isCurrent ? "page" : undefined}>
                  <span className="mint-flavor-switcher__name">
                    {option.label}
                  </span>
                  {option.description ? <span className="mint-flavor-switcher__description">
                      {option.description}
                    </span> : null}
                </a>
              </li>;
  })}
        </ul>
      </details>
    </div>;
};

<div className="mint-flavor-switcher-slot not-prose">
  <FlavorSwitcher
    current="react"
    baseHref="/doc/api-reference/widgets/instantsearch"
    options={[
{ value: "js", label: "JavaScript", description: "InstantSearch.js" },
{ value: "react", label: "React", description: "React InstantSearch" },
{ value: "vue", label: "Vue", description: "Vue InstantSearch" },
{ value: "ios", label: "iOS", description: "InstantSearch iOS" },
{ value: "android", label: "Android", description: "InstantSearch Android" },
{ value: "flutter", label: "Flutter", description: "Algolia for Flutter" },
]}
  />
</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>

```tsx Signature theme={"system"}
<InstantSearch
  indexName={string}
  searchClient={object}
  // Optional props
  initialUiState={object}
  onStateChange={function}
  stalledSearchDelay={number}
  routing={boolean | object}
  insights={boolean | object}
  future={{
    preserveSharedStateOnUnmount: boolean,
    persistHierarchicalRootCount: boolean,
  }}
/>
```

## Import

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

## About this widget

`<InstantSearch>` is the root wrapper component for all widgets and Hooks.
It takes two parameters:

* [`indexName`](/doc/api-reference/widgets/instantsearch/react#param-index-name). Your main search index
* [`searchClient`](/doc/api-reference/widgets/instantsearch/react#param-search-client).
  The search client for React InstantSearch.
  The [search client](https://github.com/algolia/algoliasearch-client-javascript)
  needs an `appId` and an `apiKey`, which you can find in the [Algolia dashboard](https://dashboard.algolia.com/account/api-keys).

See also: [Get started with React InstantSearch](/doc/guides/building-search-ui/getting-started/react)

### Middleware

React InstantSearch provides middleware to help you connect to other systems:

* **Insights.** Use the [`insights`](/doc/api-reference/widgets/insights/js) middleware to [send click and conversion events](/doc/guides/building-search-ui/events/react)
* **Generic.** With the [`middleware`](/doc/api-reference/widgets/middleware/react) API, you can inject logic into React InstantSearch. For example, to [send events to Google Analytics](/doc/guides/building-search-ui/going-further/integrate-google-analytics/react).

## Examples

```jsx JavaScript icon=code theme={"system"}
import React from "react";
import { liteClient as algoliasearch } from "algoliasearch/lite";
import { InstantSearch } from "react-instantsearch";

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

function App() {
  return (
    <InstantSearch indexName="INDEX_NAME" searchClient={searchClient}>
      {/* Widgets */}
    </InstantSearch>
  );
}
```

## Props

<ParamField body="indexName" type="string" required>
  The main index in which to search.

  ```jsx JavaScript icon=code theme={"system"}
  <InstantSearch
    // ...
    indexName="INDEX_NAME"
  >
    {/* Widgets */}
  </InstantSearch>;
  ```
</ParamField>

<ParamField body="searchClient" type="object" required>
  Provides a search client to `<InstantSearch>`.
  Read [the custom backend guidance](/doc/guides/building-search-ui/going-further/backend-search/react) on implementing a custom search client.

  The client uses a cache to avoid unnecessary search operations, so you should use a stable reference to the same search client instance rather than creating a new one on each render. Avoid inlining the function call to `algoliasearch` as the prop value, and consider instantiating the client outside your React components.

  ```jsx JavaScript icon=code theme={"system"}
  const searchClient = algoliasearch("YourApplicationID", "YourSearchOnlyAPIKey");

  function App() {
    return (
      <InstantSearch
        // ...
        searchClient={searchClient}
      >
        {/* Widgets */}
      </InstantSearch>
    );
  }
  ```
</ParamField>

<ParamField body="initialUiState" type="object">
  Provides an initial state to your React InstantSearch widgets using the [`ui-state`](/doc/api-reference/widgets/ui-state/js) object from InstantSearch.js.

  Since this sets the initial state for your UI,
  you need to include the corresponding widgets in your app.
  For example, `page: 5` as initial state only has an effect
  if you include the `pagination` widget as well.

  Replace `YourIndexName` with the name of your Algolia index.

  ```jsx JavaScript icon=code theme={"system"}
  <InstantSearch
    // ...
    initialUiState={{
      YourIndexName: {
        // Sets the initial query for the SearchBox widget
        query: "phone",
        // Sets the initial page number for the Pagination widget
        page: 5,
      },
    }}
  >
    {/* Widgets */}
  </InstantSearch>;
  ```
</ParamField>

<ParamField body="onStateChange" type="function">
  Triggered when the state changes.
  This can be helpful for performing custom logic on a state change.

  When using `onStateChange`, the instance is under your control. **You're responsible for updating the UI state** (with `setUiState`).

  <CodeGroup>
    ```jsx JavaScript theme={"system"}
    const onStateChange = ({ uiState, setUiState }) => {
      // Custom logic
      setUiState(uiState);
    };

    function App() {
      return (
        <InstantSearch
          // ...
          onStateChange={onStateChange}
        >
          {/* Widgets */}
        </InstantSearch>
      );
    }
    ```

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

    const onStateChange: InstantSearchProps["onStateChange"] = ({
      uiState,
      setUiState,
    }) => {
      // Custom logic
      setUiState(uiState);
    };

    function App() {
      return (
        <InstantSearch
          // ...
          onStateChange={onStateChange}
        >
          {/* Widgets */}
        </InstantSearch>
      );
    }
    ```
  </CodeGroup>
</ParamField>

<ParamField body="stalledSearchDelay" type="number" default={200}>
  A time period (in ms) after which the search is considered to have stalled.
  Read the [slow network guide](/doc/guides/building-search-ui/going-further/improve-performance/react) for more information.

  ```jsx JavaScript icon=code theme={"system"}
  <InstantSearch
    // ...
    stalledSearchDelay={500}
  >
    {/* Widgets */}
  </InstantSearch>;
  ```
</ParamField>

<ParamField body="routing" type="boolean | object" default={false}>
  The router configuration used to save the UI state into the URL or any client-side persistence.

  <Expandable title="routing props">
    <ParamField body="routing.router" type="object">
      This object stores the UI state.
      By default, it uses an instance of the [`history`](/doc/api-reference/widgets/history-router/react)
      router with its default parameters.

      <Expandable title="router props">
        <ParamField body="router.onUpdate" type="function">
          Adds an event listener that makes InstantSearch aware of external changes to the storage medium (such as the URL).
          Typically you'll set up a listener for `popstate`,
          which triggers a callback with the current `routeState`.
        </ParamField>

        <ParamField body="router.read" type="function">
          Reads the routing storage and returns a `routeState` object.
        </ParamField>

        <ParamField body="router.write" type="function">
          Writes the `routeState` object into the routing storage.
        </ParamField>

        <ParamField body="router.createURL" type="function">
          Transforms the `routeState` object into a URL.
          It receives an object and returns a string (which may be empty).
        </ParamField>

        <ParamField body="router.dispose" type="function">
          Cleans up all event listeners.
        </ParamField>
      </Expandable>
    </ParamField>

    <ParamField body="routing.stateMapping" type="object">
      Transforms the [`uiState`](/doc/api-reference/widgets/ui-state/react)
      into the object saved by the router.
      The default value is provided by [`simple`](/doc/api-reference/widgets/simple-state-mapping/react).

      <Expandable title="stateMapping props">
        <ParamField body="stateMapping.stateToRoute" type="function">
          Transforms a `ui-state` representation into a `routeState` object.
          It receives an object that contains the UI state of all the widgets on the page.
          It can return any object that is readable by `routeToState`.
        </ParamField>

        <ParamField body="stateMapping.routeToState" type="function">
          Transforms `routeState` into a `ui-state` representation.
          It receives an object that contains the UI state stored by the router.
          It can return any object that is readable by `stateToRoute`.
        </ParamField>
      </Expandable>
    </ParamField>
  </Expandable>

  For more information, see [Sync your URLs](/doc/guides/building-search-ui/going-further/routing-urls/react).

  You can't use [`initialUiState`](#param-initial-ui-state) with routing as the two options override each other.

  * Use `initialUiState` for simple and static use cases
  * Use `routing` for anything complex or dynamic.

  ```jsx JavaScript icon=code theme={"system"}
  <InstantSearch
    // ...
    routing={true}
  >
    {/* Widgets */}
  </InstantSearch>;
  ```
</ParamField>

<ParamField body="insights" type="boolean | InsightsProps" default={false}>
  Enables the Insights middleware and loads the [`search-insights`](https://github.com/algolia/search-insights.js) library (if not already loaded). The Insights middleware sends view and click events automatically, and lets you set up your own [click and conversion events](/doc/guides/building-search-ui/events/react).

  To use this option with an object, refer to the [Insights middleware options](/doc/api-reference/widgets/insights/react#options).

  <CodeGroup>
    ```jsx boolean theme={"system"}
    <InstantSearch
      // ...
      insights={true}
    >
      {/* Widgets */}
    </InstantSearch>;
    ```

    ```jsx object theme={"system"}
    <InstantSearch
      // ...
      insights={{
        insightsClient: window.aa,
        insightsInitParams: {
          useCookie: false,
          // …
        },
        // …
      }}
    >
      {/* Widgets */}
    </InstantSearch>;
    ```
  </CodeGroup>
</ParamField>

<ParamField body="future" type="object">
  Test new InstantSearch features without affecting others.

  <Expandable title="future props">
    <ParamField body="future.preserveSharedStateOnUnmount" type="boolean" default={false} post={["since: v7.2.0"]}>
      Changes the way `dispose` is used in the InstantSearch lifecycle.

      * If `false` (the default), each widget unmounting will also remove its state, even if multiple widgets read that UI state.
      * If `true`, each widget unmounting will only remove its state if it's the last of its type. This lets you to dynamically add and remove widgets without losing their state.

      ```jsx JavaScript icon=code theme={"system"}
      <InstantSearch
        // ...
        future={{
          preserveSharedStateOnUnmount: true,
        }}
      >
        {/* Widgets */}
      </InstantSearch>;
      ```
    </ParamField>

    <ParamField body="future.persistHierarchicalRootCount" type="boolean" default={false} post={["since: v7.4.1"]}>
      Whether to display a constant <Facet /> value count at the root of a hierarchical menu with active refinements.

      * If `false` (default), the facet value count at the root level shows the facet value count of the refined (child) facet's parent.
      * If `true`, the facet value count at the root level shows the sum of the facet value counts of all its children, with or without refined children.

      ```jsx JavaScript icon=code theme={"system"}
      <InstantSearch
        // ...
        future={{
          persistHierarchicalRootCount: true,
        }}
      >
        {/* Widgets */}
      </InstantSearch>;
      ```
    </ParamField>
  </Expandable>
</ParamField>
