--- title: useAnalytics description: A hook that provides access to the analytics provider context. Must be a descendent of [`Analytics.Provider`](/docs/api/hydrogen/2024-07/components/Analytics-provider). api_version: 2024-07 api_name: hydrogen source_url: html: https://shopify.dev/docs/api/hydrogen/2024-07/hooks/useanalytics md: https://shopify.dev/docs/api/hydrogen/2024-07/hooks/useanalytics.md --- # use​Analyticshook A hook that provides access to the analytics provider context. Must be a descendent of [`Analytics.Provider`](https://shopify.dev/docs/api/hydrogen/2024-07/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\ 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/2024-07/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 ```ts Cart ``` ### StorefrontApiErrors ```ts JsonGraphQLError[] | undefined ``` ### JsonGraphQLError ```ts ReturnType ``` ### AnalyticsContextPublishForDoc ```ts PublishPageView | PublishProductView | PublishCollectionView | PublishCartView | PublishSearchView | PublishCartUpdated | PublishProductAddedToCart | PublishProductRemovedFromCart | PublishCustomEvent ``` ### PublishPageView * event ```ts "page_viewed" ``` * payload ```ts PageViewPayload ``` void ```ts void ``` ```ts type PublishPageView = (event: 'page_viewed', payload: PageViewPayload) => void; ``` ### PageViewPayload ```ts UrlPayload & BasePayload ``` ### UrlPayload * url The url location of when this event is collected. ```ts string ``` ```ts { /** The url location of when this event is collected. */ url: 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 ``` ```ts { /** The shop data passed in from the `AnalyticsProvider`. */ shop: ShopAnalytics | null; /** The custom data passed in from the `AnalyticsProvider`. */ customData?: AnalyticsProviderProps['customData']; } ``` ### 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 ``` ```ts { /** The shop ID. */ shopId: string; /** The language code that is being displayed to user. */ acceptedLanguage: LanguageCode; /** The currency code that is being displayed to user. */ currency: CurrencyCode; /** The Hydrogen subchannel ID generated by Oxygen in the environment variable. */ hydrogenSubchannelId: string | '0'; } ``` ### PublishProductView * event ```ts "product_viewed" ``` * payload ```ts ProductViewPayload ``` void ```ts void ``` ```ts type PublishProductView = ( event: 'product_viewed', payload: ProductViewPayload, ) => void; ``` ### ProductViewPayload ```ts ProductsPayload & UrlPayload & BasePayload ``` ### ProductsPayload * products The products associated with this event. ```ts Array ``` ```ts { /** The products associated with this event. */ products: 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 ``` ```ts { /** The product id. */ id: Product['id']; /** The product title. */ title: Product['title']; /** The displaying variant price. */ price: ProductVariant['price']['amount']; /** The product vendor. */ vendor: Product['vendor']; /** The displaying variant id. */ variantId: ProductVariant['id']; /** The displaying variant title. */ variantTitle: ProductVariant['title']; /** The quantity of product. */ quantity: number; /** The product sku. */ sku?: ProductVariant['sku']; /** The product type. */ productType?: Product['productType']; } ``` ### OtherData ```ts OtherData ``` ### PublishCollectionView * event ```ts "collection_viewed" ``` * payload ```ts CollectionViewPayload ``` void ```ts void ``` ```ts type PublishCollectionView = ( event: 'collection_viewed', payload: CollectionViewPayload, ) => void; ``` ### CollectionViewPayload ```ts CollectionPayload & UrlPayload & BasePayload ``` ### CollectionPayload * collection ```ts CollectionPayloadDetails ``` ```ts { collection: CollectionPayloadDetails; } ``` ### CollectionPayloadDetails * handle The collection handle. ```ts string ``` * id The collection id. ```ts string ``` ```ts { /** The collection id. */ id: string; /** The collection handle. */ handle: string; } ``` ### PublishCartView * event ```ts "cart_viewed" ``` * payload ```ts CartViewPayload ``` void ```ts void ``` ```ts type PublishCartView = (event: 'cart_viewed', payload: CartViewPayload) => void; ``` ### CartViewPayload ```ts CartPayload & UrlPayload & BasePayload ``` ### CartPayload * cart The current cart state. ```ts CartReturn | null ``` * prevCart The previous cart state. ```ts CartReturn | null ``` ```ts { /** The current cart state. */ cart: CartReturn | null; /** The previous cart state. */ prevCart: CartReturn | null; } ``` ### PublishSearchView * event ```ts "search_viewed" ``` * payload ```ts SearchViewPayload ``` void ```ts void ``` ```ts type PublishSearchView = ( event: 'search_viewed', payload: SearchViewPayload, ) => 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 ``` ```ts { /** The search term used for the search results page */ searchTerm: string; /** The search results */ searchResults?: any; } ``` ### PublishCartUpdated * event ```ts "cart_updated" ``` * payload ```ts CartUpdatePayload ``` void ```ts void ``` ```ts type PublishCartUpdated = ( event: 'cart_updated', payload: CartUpdatePayload, ) => void; ``` ### CartUpdatePayload ```ts CartPayload & BasePayload & OtherData ``` ### PublishProductAddedToCart * event ```ts "product_added_to_cart" ``` * payload ```ts CartLineUpdatePayload ``` void ```ts void ``` ```ts type PublishProductAddedToCart = ( event: 'product_added_to_cart', payload: CartLineUpdatePayload, ) => 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 ``` ```ts { /** The previous state of the cart line that got updated. */ prevLine?: CartLine | ComponentizableCartLine; /** The current state of the cart line that got updated. */ currentLine?: CartLine | ComponentizableCartLine; } ``` ### PublishProductRemovedFromCart * event ```ts "product_removed_from_cart" ``` * payload ```ts CartLineUpdatePayload ``` void ```ts void ``` ```ts type PublishProductRemovedFromCart = ( event: 'product_removed_from_cart', payload: CartLineUpdatePayload, ) => void; ``` ### PublishCustomEvent * event ```ts `custom_${string}` ``` * payload ```ts OtherData ``` void ```ts void ``` ```ts type PublishCustomEvent = ( event: `custom_${string}`, payload: OtherData, ) => 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 ``` ```ts type SubscribePageView = ( event: 'page_viewed', callback: (payload: PageViewPayload) => void, ) => void; ``` ### SubscribeProductView * event ```ts "product_viewed" ``` * callback ```ts (payload: ProductViewPayload) => void ``` void ```ts void ``` ```ts type SubscribeProductView = ( event: 'product_viewed', callback: (payload: ProductViewPayload) => void, ) => void; ``` ### SubscribeCollectionView * event ```ts "collection_viewed" ``` * callback ```ts (payload: CollectionViewPayload) => void ``` void ```ts void ``` ```ts type SubscribeCollectionView = ( event: 'collection_viewed', callback: (payload: CollectionViewPayload) => void, ) => void; ``` ### SubscribeCartView * event ```ts "cart_viewed" ``` * callback ```ts (payload: CartViewPayload) => void ``` void ```ts void ``` ```ts type SubscribeCartView = ( event: 'cart_viewed', callback: (payload: CartViewPayload) => void, ) => void; ``` ### SubscribeSearchView * event ```ts "search_viewed" ``` * callback ```ts (payload: SearchViewPayload) => void ``` void ```ts void ``` ```ts type SubscribeSearchView = ( event: 'search_viewed', callback: (payload: SearchViewPayload) => void, ) => void; ``` ### SubscribeCartUpdated * event ```ts "cart_updated" ``` * callback ```ts (payload: CartUpdatePayload) => void ``` void ```ts void ``` ```ts type SubscribeCartUpdated = ( event: 'cart_updated', callback: (payload: CartUpdatePayload) => void, ) => void; ``` ### SubscribeProductAddedToCart * event ```ts "product_added_to_cart" ``` * callback ```ts (payload: CartLineUpdatePayload) => void ``` void ```ts void ``` ```ts type SubscribeProductAddedToCart = ( event: 'product_added_to_cart', callback: (payload: CartLineUpdatePayload) => void, ) => void; ``` ### SubscribeProductRemovedFromCart * event ```ts "product_removed_from_cart" ``` * callback ```ts (payload: CartLineUpdatePayload) => void ``` void ```ts void ``` ```ts type SubscribeProductRemovedFromCart = ( event: 'product_removed_from_cart', callback: (payload: CartLineUpdatePayload) => void, ) => void; ``` ### SubscribeCustomEvent * event ```ts `custom_${string}` ``` * callback ```ts (payload: OtherData) => void ``` void ```ts void ``` ```ts type SubscribeCustomEvent = ( event: `custom_${string}`, callback: (payload: OtherData) => void, ) => void; ``` ### 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 `` 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; } ``` ## Examples Example usage with `useAnalytics`: ### useAnalytics.register Registers a unique key with the analytics provider component, enabling custom analytics integrations to wait for a callback before sending event data. ### Examples * #### ##### 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; } ```