---
title: useAnalytics
description: >-
  A hook that provides access to the analytics provider context. Must be a
  descendent of
  [`Analytics.Provider`](/docs/api/hydrogen/2025-04/components/Analytics-provider).
api_version: 2025-05
api_name: hydrogen
source_url:
  html: 'https://shopify.dev/docs/api/hydrogen/2025-05/hooks/useanalytics'
  md: 'https://shopify.dev/docs/api/hydrogen/2025-05/hooks/useanalytics.md'
---

# use​Analytics

A hook that provides access to the analytics provider context. Must be a descendent of [`Analytics.Provider`](https://shopify.dev/docs/api/hydrogen/2025-04/components/Analytics-provider).

## Returns

* **canTrack**

  **() => boolean**

  A function to tell you the current state of if the user can be tracked by analytics. Defaults to Customer Privacy API's `window.Shopify.customerPrivacy.analyticsProcessingAllowed()`.

* **cart**

  **UserCart | DefaultCart**

  The current cart state. You can overwrite the type by passing a generic

* **customData**

  **Record\<string, unknown>**

  The custom data passed in from the `AnalyticsProvider`.

* **prevCart**

  **UserCart | DefaultCart**

  The previous cart state. You can overwrite the type by passing a generic

* **publish**

  **AnalyticsContextPublishForDoc**

  A function to publish an analytics event.

* **register**

  **(key: string) => { ready: () => void; }**

  A function to register with the analytics provider. It holds the first browser load events until all registered key has executed the supplied `ready` function. [See example register usage](https://shopify.dev/docs/api/hydrogen/2025-04/hooks/useanalytics#example-useanalytics.register).

* **shop**

  **Promise\<ShopAnalytics | null> | ShopAnalytics | null**

  The shop configuration required to publish events to Shopify.

* **subscribe**

  **AnalyticsContextSubscribeForDoc**

  A function to subscribe to analytics events.

### DefaultCart

```ts
Promise<CartReturn | null> | CartReturn | null
```

### CartReturn

```ts
Cart & {
  errors?: StorefrontApiErrors;
}
```

### Cart



### StorefrontApiErrors

```ts
JsonGraphQLError[] | undefined
```

### JsonGraphQLError



### AnalyticsContextPublishForDoc

```ts
PublishPageView | PublishProductView | PublishCollectionView | PublishCartView | PublishSearchView | PublishCartUpdated | PublishProductAddedToCart | PublishProductRemovedFromCart | PublishCustomEvent
```

### PublishPageView

* event

  ```ts
  "page_viewed"
  ```

* payload

  ```ts
  PageViewPayload
  ```

void

```ts
void
```

### PageViewPayload

```ts
UrlPayload & BasePayload
```

### UrlPayload

* url

  The url location of when this event is collected.

  ```ts
  string
  ```

### BasePayload

* customData

  The custom data passed in from the \`AnalyticsProvider\`.

  ```ts
  Record<string, unknown>
  ```

* shop

  The shop data passed in from the \`AnalyticsProvider\`.

  ```ts
  ShopAnalytics | null
  ```

### ShopAnalytics

* acceptedLanguage

  The language code that is being displayed to user.

  ```ts
  LanguageCode
  ```

* currency

  The currency code that is being displayed to user.

  ```ts
  CurrencyCode
  ```

* hydrogenSubchannelId

  The Hydrogen subchannel ID generated by Oxygen in the environment variable.

  ```ts
  string | '0'
  ```

* shopId

  The shop ID.

  ```ts
  string
  ```

### PublishProductView

* event

  ```ts
  "product_viewed"
  ```

* payload

  ```ts
  ProductViewPayload
  ```

void

```ts
void
```

### ProductViewPayload

```ts
ProductsPayload & UrlPayload & BasePayload
```

### ProductsPayload

* products

  The products associated with this event.

  ```ts
  Array<ProductPayload & OtherData>
  ```

### ProductPayload

* id

  The product id.

  ```ts
  string
  ```

* price

  The displaying variant price.

  ```ts
  string
  ```

* productType

  The product type.

  ```ts
  string
  ```

* quantity

  The quantity of product.

  ```ts
  number
  ```

* sku

  The product sku.

  ```ts
  string
  ```

* title

  The product title.

  ```ts
  string
  ```

* variantId

  The displaying variant id.

  ```ts
  string
  ```

* variantTitle

  The displaying variant title.

  ```ts
  string
  ```

* vendor

  The product vendor.

  ```ts
  string
  ```

### OtherData



### PublishCollectionView

* event

  ```ts
  "collection_viewed"
  ```

* payload

  ```ts
  CollectionViewPayload
  ```

void

```ts
void
```

### CollectionViewPayload

```ts
CollectionPayload & UrlPayload & BasePayload
```

### CollectionPayload

* collection

  ```ts
  CollectionPayloadDetails
  ```

### CollectionPayloadDetails

* handle

  The collection handle.

  ```ts
  string
  ```

* id

  The collection id.

  ```ts
  string
  ```

### PublishCartView

* event

  ```ts
  "cart_viewed"
  ```

* payload

  ```ts
  CartViewPayload
  ```

void

```ts
void
```

### CartViewPayload

```ts
CartPayload & UrlPayload & BasePayload
```

### CartPayload

* cart

  The current cart state.

  ```ts
  CartReturn | null
  ```

* prevCart

  The previous cart state.

  ```ts
  CartReturn | null
  ```

### PublishSearchView

* event

  ```ts
  "search_viewed"
  ```

* payload

  ```ts
  SearchViewPayload
  ```

void

```ts
void
```

### SearchViewPayload

```ts
SearchPayload & UrlPayload & BasePayload
```

### SearchPayload

* searchResults

  The search results

  ```ts
  any
  ```

* searchTerm

  The search term used for the search results page

  ```ts
  string
  ```

### PublishCartUpdated

* event

  ```ts
  "cart_updated"
  ```

* payload

  ```ts
  CartUpdatePayload
  ```

void

```ts
void
```

### CartUpdatePayload

```ts
CartPayload & BasePayload & OtherData
```

### PublishProductAddedToCart

* event

  ```ts
  "product_added_to_cart"
  ```

* payload

  ```ts
  CartLineUpdatePayload
  ```

void

```ts
void
```

### CartLineUpdatePayload

```ts
CartLinePayload & CartPayload & BasePayload & OtherData
```

### CartLinePayload

* currentLine

  The current state of the cart line that got updated.

  ```ts
  CartLine | ComponentizableCartLine
  ```

* prevLine

  The previous state of the cart line that got updated.

  ```ts
  CartLine | ComponentizableCartLine
  ```

### PublishProductRemovedFromCart

* event

  ```ts
  "product_removed_from_cart"
  ```

* payload

  ```ts
  CartLineUpdatePayload
  ```

void

```ts
void
```

### PublishCustomEvent

* event

  ```ts
  `custom_${string}`
  ```

* payload

  ```ts
  OtherData
  ```

void

```ts
void
```

### AnalyticsContextSubscribeForDoc

```ts
SubscribePageView | SubscribeProductView | SubscribeCollectionView | SubscribeCartView | SubscribeSearchView | SubscribeCartUpdated | SubscribeProductAddedToCart | SubscribeProductRemovedFromCart | SubscribeCustomEvent
```

### SubscribePageView

* event

  ```ts
  "page_viewed"
  ```

* callback

  ```ts
  (payload: PageViewPayload) => void
  ```

void

```ts
void
```

### SubscribeProductView

* event

  ```ts
  "product_viewed"
  ```

* callback

  ```ts
  (payload: ProductViewPayload) => void
  ```

void

```ts
void
```

### SubscribeCollectionView

* event

  ```ts
  "collection_viewed"
  ```

* callback

  ```ts
  (payload: CollectionViewPayload) => void
  ```

void

```ts
void
```

### SubscribeCartView

* event

  ```ts
  "cart_viewed"
  ```

* callback

  ```ts
  (payload: CartViewPayload) => void
  ```

void

```ts
void
```

### SubscribeSearchView

* event

  ```ts
  "search_viewed"
  ```

* callback

  ```ts
  (payload: SearchViewPayload) => void
  ```

void

```ts
void
```

### SubscribeCartUpdated

* event

  ```ts
  "cart_updated"
  ```

* callback

  ```ts
  (payload: CartUpdatePayload) => void
  ```

void

```ts
void
```

### SubscribeProductAddedToCart

* event

  ```ts
  "product_added_to_cart"
  ```

* callback

  ```ts
  (payload: CartLineUpdatePayload) => void
  ```

void

```ts
void
```

### SubscribeProductRemovedFromCart

* event

  ```ts
  "product_removed_from_cart"
  ```

* callback

  ```ts
  (payload: CartLineUpdatePayload) => void
  ```

void

```ts
void
```

### SubscribeCustomEvent

* event

  ```ts
  `custom_${string}`
  ```

* callback

  ```ts
  (payload: OtherData) => void
  ```

void

```ts
void
```

Examples

### Examples

* #### example

  ##### Description

  This is the default example

  ##### JavaScript

  ```js
  import {useAnalytics} from '@shopify/hydrogen';
  import {useEffect} from 'react';

  export function CustomAnalytics() {
    const {subscribe, register} = useAnalytics();
    const {ready} = register('CustomAnalytics'); // unique string identifier

    useEffect(() => {
      // Triggers on every page navigation
      subscribe('page_viewed', (data) => {
        console.log('CustomAnalytics - Page viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.ProductView>`
      subscribe('product_viewed', (data) => {
        console.log('CustomAnalytics - Product viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.CollectionView>`
      subscribe('collection_viewed', (data) => {
        console.log('CustomAnalytics - Collection viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.CartView>`
      subscribe('cart_viewed', (data) => {
        console.log('CustomAnalytics - Cart viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.SearchView>`
      subscribe('search_viewed', (data) => {
        console.log('CustomAnalytics - Search viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.CustomView type="custom_promotion_viewed">`
      subscribe('custom_promotion_viewed', (data) => {
        console.log('CustomAnalytics - Promotion viewed:', data);
      });

      // Triggers when the cart is updated
      subscribe('cart_updated', (data) => {
        console.log('CustomAnalytics - Cart updated:', data);
      });

      // Triggers when an existing cart line increases in quantity or a new cart line is added
      subscribe('product_added_to_cart', (data) => {
        console.log('CustomAnalytics - Product added to cart:', data);
      });

      // Triggers when an existing cart line decreases in quantity or a cart line is removed
      subscribe('product_removed_from_cart', (data) => {
        console.log('CustomAnalytics - Product removed from cart:', data);
      });

      // Register the CustomAnalytics component as ready
      ready();
    }, []);

    return null;
  }
  ```

  ##### TypeScript

  ```ts
  import {
    type PageViewPayload,
    type ProductViewPayload,
    type CollectionViewPayload,
    type CartViewPayload,
    type CartUpdatePayload,
    type CartLineUpdatePayload,
    type SearchViewPayload,
    useAnalytics,
  } from '@shopify/hydrogen';
  import {useEffect} from 'react';

  export function CustomAnalytics() {
    const {subscribe, register} = useAnalytics();
    const {ready} = register('CustomAnalytics'); // unique string identifier

    useEffect(() => {
      // Triggers on every page navigation
      subscribe('page_viewed', (data: PageViewPayload) => {
        console.log('CustomAnalytics - Page viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.ProductView>`
      subscribe('product_viewed', (data: ProductViewPayload) => {
        console.log('CustomAnalytics - Product viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.CollectionView>`
      subscribe('collection_viewed', (data: CollectionViewPayload) => {
        console.log('CustomAnalytics - Collection viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.CartView>`
      subscribe('cart_viewed', (data: CartViewPayload) => {
        console.log('CustomAnalytics - Cart viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.SearchView>`
      subscribe('search_viewed', (data: SearchViewPayload) => {
        console.log('CustomAnalytics - Search viewed:', data);
      });

      // Triggers on a page that uses `<Analytics.CustomView type="custom_promotion_viewed">`
      subscribe('custom_promotion_viewed', (data: unknown) => {
        console.log('CustomAnalytics - Promotion viewed:', data);
      });

      // Triggers when the cart is updated
      subscribe('cart_updated', (data: CartUpdatePayload) => {
        console.log('CustomAnalytics - Cart updated:', data);
      });

      // Triggers when an existing cart line increases in quantity or a new cart line is added
      subscribe('product_added_to_cart', (data: CartLineUpdatePayload) => {
        console.log('CustomAnalytics - Product added to cart:', data);
      });

      // Triggers when an existing cart line decreases in quantity or a cart line is removed
      subscribe('product_removed_from_cart', (data: CartLineUpdatePayload) => {
        console.log('CustomAnalytics - Product removed from cart:', data);
      });

      // Register the CustomAnalytics component as ready
      ready();
    }, []);

    return null;
  }
  ```

* ####

  ##### Description

  Registers a unique key with the analytics provider component, enabling custom analytics integrations to wait for a callback before sending event data.

  ##### JavaScript

  ```js
  import {
    type PageViewPayload,
    useAnalytics,
    useLoadScript,
  } from '@shopify/hydrogen';
  import {useEffect} from 'react';

  export function MyAnalytics() {
    const {subscribe, register} = useAnalytics();

    // Load the 3p analytics script
    const scriptStatus = useLoadScript(
      'https://example.com/some-3p-analytics-script.js',
    );

    // unique string identifier
    const {ready} = register('MyAnalytics');

    useEffect(() => {
      // Make sure the 3p script is loaded
      if (scriptStatus !== 'done') return;

      // Initialize the 3p analytics script

      // Subscribe to analytics events
      subscribe('page_viewed', (data: PageViewPayload) => {
        // report to 3p analytics
      });

      // Register the MyAnalytics component as ready
      ready();
    }, []);

    return null;
  }
  ```
