--- title: useAnalytics description: A hook that provides access to the analytics provider context. api_version: 2026-04 api_name: hydrogen source_url: html: 'https://shopify.dev/docs/api/hydrogen/latest/hooks/useanalytics' md: 'https://shopify.dev/docs/api/hydrogen/latest/hooks/useanalytics.md' --- # useAnalytics A hook that provides access to the analytics provider context. Must be a descendent of [`Analytics.Provider`](https://shopify.dev/docs/api/hydrogen/2026-04/components/analytics/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\** 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/hooks/useanalytics#example-useanalytics.register). * **shop** **Promise\ | 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 ```ts Cart & { errors?: StorefrontApiErrors; } ``` ### Cart * attributes The cart's attributes. ```ts { __typename?: "Attribute"; key?: string; value?: string; }[] ``` * buyerIdentity The cart's buyer identity. ```ts CartType['buyerIdentity'] ``` * checkoutUrl The checkout URL for the cart, if the cart has been created in the Storefront API. ```ts string ``` * cost The cost for the cart, including the subtotal, total, taxes, and duties. ```ts CartType['cost'] ``` * discountCodes The discount codes applied to the cart. ```ts { __typename?: "CartDiscountCode"; applicable?: boolean; code?: string; }[] ``` * id The cart's ID if it has been created through the Storefront API. ```ts string ``` * lines The cart lines. ```ts Array ``` * note The cart's note. ```ts string ``` * totalQuantity The total number of items in the cart, across all lines. If there are no lines, then the value is 0. ```ts number ``` ### StorefrontApiErrors ```ts JsonGraphQLError[] | undefined ``` ### JsonGraphQLError * extensions Reserved for implementors to extend the protocol however they see fit, and hence there are no additional restrictions on its contents. ```ts { [key: string]: unknown; } ``` * locations If an error can be associated to a particular point in the requested GraphQL document, it should contain a list of locations. ```ts { line: number; column: number; }[] ``` * message ```ts string ``` * name ```ts string ``` * path If an error can be associated to a particular field in the GraphQL result, it \_must\_ contain an entry with the key \`path\` that details the path of the response field which experienced the error. This allows clients to identify whether a null result is intentional or caused by a runtime error. ```ts (string | number)[] ``` * stack ```ts string ``` ### AnalyticsContextPublishForDoc ```ts PublishPageView | PublishProductView | PublishCollectionView | PublishCartView | PublishSearchView | PublishCartUpdated | PublishProductAddedToCart | PublishProductRemovedFromCart | PublishCustomEvent ``` ### PublishPageView * event ```ts "page_viewed" ``` * payload ```ts PageViewPayload ``` returns ```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 ``` * 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 ``` ### CurrencyCode Supports CurrencyCode from both Storefront API and Customer Account API. The APIs may have different CurrencyCode enums (e.g., Customer Account API added USDC in 2025-10, but Storefront API doesn't support USDC in 2025-10). This union type ensures useMoney works with data from either API. ```ts StorefrontApiCurrencyCode | CustomerAccountApiCurrencyCode ``` ### PublishProductView * event ```ts "product_viewed" ``` * payload ```ts ProductViewPayload ``` returns ```ts void ``` ### ProductViewPayload ```ts ProductsPayload & UrlPayload & BasePayload ``` ### ProductsPayload * products The products associated with this event. ```ts Array ``` ### 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 ``` returns ```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 ``` returns ```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 ``` returns ```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 ``` returns ```ts void ``` ### CartUpdatePayload ```ts CartPayload & BasePayload & OtherData ``` ### PublishProductAddedToCart * event ```ts "product_added_to_cart" ``` * payload ```ts CartLineUpdatePayload ``` returns ```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 ``` returns ```ts void ``` ### PublishCustomEvent * event ```ts `custom_${string}` ``` * payload ```ts OtherData ``` returns ```ts void ``` ### AnalyticsContextSubscribeForDoc ```ts SubscribePageView | SubscribeProductView | SubscribeCollectionView | SubscribeCartView | SubscribeSearchView | SubscribeCartUpdated | SubscribeProductAddedToCart | SubscribeProductRemovedFromCart | SubscribeCustomEvent ``` ### SubscribePageView * event ```ts "page_viewed" ``` * callback ```ts (payload: PageViewPayload) => void ``` returns ```ts void ``` ### SubscribeProductView * event ```ts "product_viewed" ``` * callback ```ts (payload: ProductViewPayload) => void ``` returns ```ts void ``` ### SubscribeCollectionView * event ```ts "collection_viewed" ``` * callback ```ts (payload: CollectionViewPayload) => void ``` returns ```ts void ``` ### SubscribeCartView * event ```ts "cart_viewed" ``` * callback ```ts (payload: CartViewPayload) => void ``` returns ```ts void ``` ### SubscribeSearchView * event ```ts "search_viewed" ``` * callback ```ts (payload: SearchViewPayload) => void ``` returns ```ts void ``` ### SubscribeCartUpdated * event ```ts "cart_updated" ``` * callback ```ts (payload: CartUpdatePayload) => void ``` returns ```ts void ``` ### SubscribeProductAddedToCart * event ```ts "product_added_to_cart" ``` * callback ```ts (payload: CartLineUpdatePayload) => void ``` returns ```ts void ``` ### SubscribeProductRemovedFromCart * event ```ts "product_removed_from_cart" ``` * callback ```ts (payload: CartLineUpdatePayload) => void ``` returns ```ts void ``` ### SubscribeCustomEvent * event ```ts `custom_${string}` ``` * callback ```ts (payload: OtherData) => void ``` returns ```ts void ``` Examples ### Examples * #### 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 `` subscribe('product_viewed', (data) => { console.log('CustomAnalytics - Product viewed:', data); }); // Triggers on a page that uses `` subscribe('collection_viewed', (data) => { console.log('CustomAnalytics - Collection viewed:', data); }); // Triggers on a page that uses `` subscribe('cart_viewed', (data) => { console.log('CustomAnalytics - Cart viewed:', data); }); // Triggers on a page that uses `` subscribe('search_viewed', (data) => { console.log('CustomAnalytics - Search viewed:', data); }); // Triggers on a page that uses `` 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 `` subscribe('product_viewed', (data: ProductViewPayload) => { console.log('CustomAnalytics - Product viewed:', data); }); // Triggers on a page that uses `` subscribe('collection_viewed', (data: CollectionViewPayload) => { console.log('CustomAnalytics - Collection viewed:', data); }); // Triggers on a page that uses `` subscribe('cart_viewed', (data: CartViewPayload) => { console.log('CustomAnalytics - Cart viewed:', data); }); // Triggers on a page that uses `` subscribe('search_viewed', (data: SearchViewPayload) => { console.log('CustomAnalytics - Search viewed:', data); }); // Triggers on a page that uses `` 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; } ``` ***