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

# Integrate Google Analytics

> Get insights from user searches in your React InstantSearch app.

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

Although Algolia provides analytics tailored to your search implementation,
you might want to send your search data to your existing analytics tools.

To do this, implement some custom middleware:

<Steps>
  <Step title="Set up Google Analytics">
    See [Set up the Google tag with gtag.js](https://developers.google.com/tag-platform/gtagjs).
  </Step>

  <Step title="Create the middleware to send events">
    In the event listener, send events to Google Analytics.
    This example debounces the event for 3 seconds but adjust this to your needs.

    ```js JavaScript icon="code" theme={"system"}
    function googleAnalyticsMiddleware() {
      let timer;
      const sendEventDebounced = () => {
        clearTimeout(timer);
        timer = setTimeout(() => {
          gtag('event', 'page_view', {
            page_location: window.location.pathname + window.location.search,
          });
        }, 3000);
      });

      return {
        onStateChange() {
          sendEventDebounced();
        },
        subscribe() {},
        unsubscribe() {},
      };
    }
    ```
  </Step>

  <Step title="Inject the middleware into the InstantSearch lifecycle">
    ```jsx React icon=code theme={"system"}
    import { useInstantSearch } from "react-instantsearch";

    function Middleware() {
      const { addMiddlewares } = useInstantsearch();

      useLayoutEffect(() => {
        return addMiddlewares(googleAnalyticsMiddleware);
      }, []);

      return null;
    }

    function Search() {
      return (
        <InstantSearch searchClient={searchClient} indexName="instant_search">
          <Middleware />
        </InstantSearch>
      );
    }
    ```
  </Step>
</Steps>
