VTEX Ads React Package Quickstart
Get started with @vtex/ads-react package for React-specific components and hooks to integrate VTEX Ads into React applications.
The @vtex/ads-react package provides React-specific components and hooks for integrating VTEX Ads into React applications. It offers a declarative API with built-in loading states, error handling, and request batching.
Installation
Install the package using npm or yarn:
_10npm install @vtex/ads-react_10# or_10yarn add @vtex/ads-react
The @vtex/ads-react package automatically includes @vtex/ads-core as a dependency.
Basic Usage
Setting up the AdsProvider
Before requesting any ads, wrap your app or page component tree with the <AdsProvider>. This provider is responsible for managing ad requests and distributing results to child components.
_28import React from "react";_28import { AdsProvider } from "@vtex/ads-react";_28import {_28 intelligentSearchFetcher,_28 intelligentSearchMatcher,_28} from "@vtex/ads-core";_28_28function App() {_28 return (_28 <AdsProvider_28 identity={{_28 accountName: "your-account-name",_28 publisherId: "your-publisher-id",_28 userId: "user-123",_28 sessionId: "session-456",_28 channel: "web", // optional: "web" | "mobile"_28 }}_28 hydrationStrategy={{_28 fetcher: intelligentSearchFetcher,_28 matcher: intelligentSearchMatcher,_28 }}_28 >_28 <YourAppContent />_28 </AdsProvider>_28 );_28}_28_28export default App;
You only need one <AdsProvider> around the subtree where ads will be requested.
Please refer to the VTEX Ads Core Package Custom Hydration guide for more details on configuring the hydration strategy.
Calling the useAds hook
Call useAds() inside your component to request ads for a specific placement:
_10const { ads, isLoading, error } = useAds({_10 placement: "search_top_product",_10 type: "product",_10 amount: 3,_10 term: "smartphone",_10});
The ads hooks will return an object with the following properties:
ads, an array of sponsored items matching the criteria.isLoading, which istruewhile the request is in progress.error, that will be populated if the request fails.
You can call useAds() multiple times within the same component to request different placements.
_13const { ads: searchAds, isLoading: isSearchAdsLoading } = useAds({_13 placement: "search_top_product",_13 type: "product",_13 amount: 2,_13 term: "tv",_13});_13_13const { ads: shelfAds, isLoading: isShelfAdsLoading } = useAds({_13 placement: "search_top-shelf_product",_13 type: "product",_13 amount: 10,_13 term: "tv",_13});