Skip to content

Repository files navigation

Meta Pixel for React

npm versionnpm downloadsLicense: MIT

The most powerful and developer-friendly Meta Pixel integration for React.

Built on top of @adkit.so/meta-pixel, this package provides a seamless, type-safe Meta Pixel experience with advanced features like event deduplication, multiple pixel support, and beautiful debug logging.

📚 Table of Contents

✨ Features

  • TypeScript Support - Full TypeScript support with autocomplete for all official events and parameters
  • 🎯 Custom Events Support - Track custom events with full type safety and flexible data structures
  • 🚦 Event Deduplication - Support for preventing duplicate events with event IDs
  • 🔌 Multiple Pixels Support - Load and manage multiple pixel IDs effortlessly
  • 🐛 Debug Mode - Beautiful styled console logs for development and debugging
  • 🏠 Localhost Support - Easy configuration to enable/disable tracking on localhost
  • ⚛️ React Context Pattern - Clean Provider/Hook pattern that feels native to React

📱 Using Next.js?

Use @adkit.so/meta-pixel-next instead! It provides:

  • Auto PageView tracking on route changes (this package doesn't do that)
  • Simple <MetaPixel /> component - no Provider needed
  • Environment variable support (NEXT_PUBLIC_META_PIXEL_ID)
npm install @adkit.so/meta-pixel-next

⚠️ Important: PageView Tracking on Route Changes

This package tracks PageView on initial load only. It does NOT automatically track PageView when navigating between pages in a Single Page Application (SPA).

Why?

React apps use client-side routing (React Router, etc.) which doesn't trigger full page reloads. The Meta Pixel script only fires PageView once when the page loads.

How to handle route changes?

Option 1: Use the Next.js package (recommended for Next.js)

npm install @adkit.so/meta-pixel-next

Option 2: Manually track PageView on route changes

// With React Routerimport{useEffect}from'react'import{useLocation}from'react-router-dom'import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionRouteChangeTracker(){constlocation=useLocation()constmeta=useMetaPixel()constisFirstRender=useRef(true)useEffect(()=>{// Skip first render (initial PageView is auto-tracked)if(isFirstRender.current){isFirstRender.current=falsereturn}// Track PageView on route changeif(meta.isLoaded()){meta.track('PageView')}},[location.pathname])returnnull}// Add to your AppfunctionApp(){return(<MetaPixelProviderpixelIds="YOUR_PIXEL_ID"><RouteChangeTracker/><YourRoutes/></MetaPixelProvider>)}

⚡ Quick Start

npm install @adkit.so/meta-pixel-react
import{MetaPixelProvider,useMetaPixel}from'@adkit.so/meta-pixel-react'// 1. Wrap your appfunctionApp(){return(<MetaPixelProviderpixelIds="YOUR_PIXEL_ID"><YourApp/></MetaPixelProvider>)}// 2. Track events anywherefunctionProductPage(){constmeta=useMetaPixel()functionhandlePurchase(){meta.track('Purchase',{value: 99.99,currency: 'USD'})}return<buttononClick={handlePurchase}>Buy Now</button>}

That's it! 🎉

📦 Installation

npm install @adkit.so/meta-pixel-react
yarn add @adkit.so/meta-pixel-react
pnpm add @adkit.so/meta-pixel-react

⚙️ Configuration

Basic Setup

Wrap your app with the MetaPixelProvider component:

import{MetaPixelProvider}from'@adkit.so/meta-pixel-react'functionApp(){return(<MetaPixelProviderpixelIds="YOUR_PIXEL_ID"autoTrackPageView={true}debug={false}enableLocalhost={false}><YourApp/></MetaPixelProvider>)}

Configuration Options

OptionTypeDefaultDescription
pixelIdsstring | string[]requiredSingle pixel ID or array of pixel IDs
autoTrackPageViewbooleantrueAutomatically track PageView on initialization
debugbooleanfalseEnable styled console logs with background colors
enableLocalhostbooleanfalseEnable tracking on localhost (useful for testing)
childrenReactNoderequiredYour React components

Multiple Pixels Example

<MetaPixelProviderpixelIds={['PIXEL_ID_1','PIXEL_ID_2','PIXEL_ID_3']}debug={true}enableLocalhost={true}><App/></MetaPixelProvider>

Using Environment Variables

// .env.localMETA_PIXEL_ID=123456789012345REACT_APP_META_PIXEL_ID=123456789012345
// App.tsx<MetaPixelProviderpixelIds={import.meta.env.META_PIXEL_ID}><App/></MetaPixelProvider>

💡 Usage

The useMetaPixel() hook provides direct access to the Meta Pixel instance with all tracking methods. It must be used within a MetaPixelProvider.

Basic Usage

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionProductPage(){constmeta=useMetaPixel()functionhandleAddToCart(){meta.track('AddToCart',{content_name: 'Wireless Headphones',content_ids: ['SKU_789'],value: 149.99,currency: 'USD'})}return<buttononClick={handleAddToCart}>Add to Cart</button>}

Tracking on Component Mount

import{useEffect}from'react'import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionProductPage({ product }){constmeta=useMetaPixel()useEffect(()=>{// Track page view when component mountsmeta.track('ViewContent',{content_name: product.name,content_ids: [product.id],value: product.price,currency: 'USD'})},[product.id])return<div>{product.name}</div>}

With Event Deduplication

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionCheckoutPage(){constmeta=useMetaPixel()asyncfunctionhandlePurchase(){constorderId=awaitprocessOrder()meta.track('Purchase',{value: 299.99,currency: 'USD',content_ids: ['SKU_123']},{eventID: `order-${orderId}`// Prevents duplicates})}return<buttononClick={handlePurchase}>Complete Purchase</button>}

Check if Pixel is Loaded

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionMyComponent(){constmeta=useMetaPixel()functiontrackIfReady(){if(meta.isLoaded())meta.track('Purchase',{value: 99.99,currency: 'USD'})elseconsole.log('Pixel not loaded yet')}return<buttononClick={trackIfReady}>Buy Now</button>}

🐛 Debug Mode

When debug={true}, you'll see beautiful styled console logs:

  • 🔵 [Meta Pixel] Info messages (blue background)
  • [Meta Pixel] Success messages (green background)
  • ⚠️[Meta Pixel] Warning messages (orange background)

Example output:

[Meta Pixel] Initializing Meta Pixel... { pixelIds: [...], autoTrackPageView: true }
[Meta Pixel] ✓ Meta Pixel initialized successfully
[Meta Pixel] Tracking standard event: "Purchase" { data: {...}, eventData: {...} }
<MetaPixelProviderpixelIds="YOUR_PIXEL_ID"debug={true}><App/></MetaPixelProvider>

📊 Standard Events

All Meta Pixel standard events are supported with full TypeScript autocomplete. These events help you track important actions on your website and optimize your ad campaigns.

EventDescriptionCommon Use Cases
AddPaymentInfoPayment info addedCheckout flow
AddToCartItem added to shopping cartE-commerce
AddToWishlistItem added to wishlistE-commerce
CompleteRegistrationUser completed registrationSign-ups, account creation
ContactUser contacted businessContact forms
CustomizeProductProduct customization startedProduct configurators
DonateDonation madeNon-profits
FindLocationLocation finder usedStore locators
InitiateCheckoutCheckout process startedE-commerce funnels
LeadLead submittedLead generation forms
PurchasePurchase completedTransaction confirmation
ScheduleAppointment scheduledBooking systems
SearchSearch performedSite search
StartTrialTrial startedSaaS applications
SubmitApplicationApplication submittedJob boards, loan applications
SubscribeSubscription startedNewsletters, subscriptions
ViewContentContent viewedProduct pages, blog posts

You can find the official list of standard events here.

Example Usage

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionEcommerceExample(){constmeta=useMetaPixel()functiontrackPurchase(){meta.track('Purchase',{value: 299.99,currency: 'USD',content_ids: ['SKU_12345'],content_type: 'product',num_items: 1})}functiontrackLead(){meta.track('Lead',{content_name: 'Newsletter Signup',content_category: 'Marketing'})}functiontrackSearch(query: string){meta.track('Search',{search_string: query})}return(<div><buttononClick={trackPurchase}>Complete Purchase</button><buttononClick={trackLead}>Sign Up</button><inputonChange={(e)=>trackSearch(e.target.value)}placeholder="Search..."/></div>)}

📋 Event Data Parameters

All event parameters are optional but help improve ad targeting and conversion tracking. Here are the most common ones:

ParameterTypeDescriptionExample
valuenumberMonetary value of the event99.99
currencystringISO 4217 currency code'USD', 'EUR', 'GBP'
content_idsstring[]Product IDs or SKUs['SKU_123', 'SKU_456']
content_typestringType of content'product', 'product_group'
content_namestringName of page/product'Blue T-Shirt'
content_categorystringCategory of page/product'Apparel', 'Electronics'
contentsArray<{id, quantity}>Detailed product information[{id: 'SKU_123', quantity: 2}]
num_itemsnumberNumber of items3
search_stringstringSearch query'running shoes'
statusbooleanRegistration/subscription statustrue
predicted_ltvnumberPredicted lifetime value of customer450.00

You can find the list of properties here.

Complete E-commerce Example

import{useState,useEffect}from'react'import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionProductPage(){constmeta=useMetaPixel()const[product]=useState({id: 'SKU_789',name: 'Wireless Headphones',price: 149.99,category: 'Electronics'})// Track page view when component mountsuseEffect(()=>{meta.track('ViewContent',{content_ids: [product.id],content_type: 'product',content_name: product.name,content_category: product.category,value: product.price,currency: 'USD'})},[product.id])functionhandleAddToCart(){meta.track('AddToCart',{content_ids: [product.id],content_type: 'product',content_name: product.name,value: product.price,currency: 'USD'})}asyncfunctionhandlePurchase(){constorderId=awaitprocessOrder()meta.track('Purchase',{content_ids: [product.id],content_type: 'product',value: product.price,currency: 'USD',num_items: 1},{eventID: orderId// For deduplication})}return(<div><h1>{product.name}</h1><p>${product.price}</p><buttononClick={handleAddToCart}>Add to Cart</button><buttononClick={handlePurchase}>Buy Now</button></div>)}

🚀 Advanced Usage

Custom Events

Track custom events specific to your business:

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionPricingPage(){constmeta=useMetaPixel()functiontrackPricingView(){meta.trackCustom('PricingPageViewed',{plan: 'enterprise',duration: 'annual'})}functiontrackVideoComplete(){meta.trackCustom('VideoWatched',{video_id: 'intro_2024',watch_percentage: 100})}return(<div><buttononClick={trackPricingView}>View Pricing</button><videoonEnded={trackVideoComplete}>Your video</video></div>)}

Event Deduplication

Prevent duplicate event tracking by using unique event IDs. This is crucial when tracking conversions from both client and server (Conversions API):

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionCheckoutPage(){constmeta=useMetaPixel()asyncfunctionprocessOrder(){constorderId=awaitcreateOrder()// Use order ID as event ID to prevent duplicatesmeta.track('Purchase',{value: 299.99,currency: 'USD',content_ids: ['SKU_123']},{eventID: `order-${orderId}`})// Even if this fires multiple times or from server too,// Meta will deduplicate based on eventID}return<buttononClick={processOrder}>Complete Order</button>}

Conditional Tracking

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionRegisterPage(){constmeta=useMetaPixel()const{ user }=useAuth()asyncfunctionhandleRegistration(){// Only track if pixel is loadedif(!meta.isLoaded()){console.warn('Meta Pixel not loaded yet')return}// Track registration with user contextmeta.track('CompleteRegistration',{status: true,content_name: user.accountType,value: user.predictedLTV})}return<buttononClick={handleRegistration}>Sign Up</button>}

Lead Form Example

import{useState,FormEvent}from'react'import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionContactForm(){constmeta=useMetaPixel()const[formData,setFormData]=useState({name: '',email: ''})asyncfunctionhandleSubmit(e: FormEvent){e.preventDefault()// Track the leadmeta.track('Lead',{content_name: 'Contact Form Submission',content_category: 'Contact',value: 10.00// Estimated lead value})awaitsubmitForm(formData)}return(<formonSubmit={handleSubmit}><inputtype="text"value={formData.name}onChange={(e)=>setFormData({ ...formData,name: e.target.value})}placeholder="Name"required/><inputtype="email"value={formData.email}onChange={(e)=>setFormData({ ...formData,email: e.target.value})}placeholder="Email"required/><buttontype="submit">Submit</button></form>)}

Search Functionality Example

import{useState}from'react'import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionSearchBar(){constmeta=useMetaPixel()const[query,setQuery]=useState('')functionhandleSearch(e: FormEvent){e.preventDefault()meta.track('Search',{search_string: query})performSearch(query)}return(<formonSubmit={handleSearch}><inputtype="text"value={query}onChange={(e)=>setQuery(e.target.value)}placeholder="Search products..."/><buttontype="submit">Search</button></form>)}

🔄 Alternative Patterns

While the Provider pattern is recommended for most React applications, we offer alternative patterns if you prefer different approaches:

Pattern 1: Provider (Recommended)

import{MetaPixelProvider,useMetaPixel}from'@adkit.so/meta-pixel-react'functionApp(){return(<MetaPixelProviderpixelIds="YOUR_PIXEL_ID"><Component/></MetaPixelProvider>)}functionComponent(){constmeta=useMetaPixel()meta.track('Purchase',{value: 99,currency: 'USD'})}

Pros: Clean React Context pattern, explicit initialization, works well with other providers

Pattern 2: Hook with Config

import{useMetaPixel}from'@adkit.so/meta-pixel-react'functionApp(){// Initialize once at rootuseMetaPixel({pixelIds: 'YOUR_PIXEL_ID'})return<Component/>}functionComponent(){// Use anywhere without configconstmeta=useMetaPixel()meta.track('Purchase',{value: 99,currency: 'USD'})}

Pros: No wrapper component, minimal code, still uses hooks

Pattern 3: Init Function

import{initMetaPixel,useMetaPixel}from'@adkit.so/meta-pixel-react'// In main.tsx or index.tsxinitMetaPixel({pixelIds: 'YOUR_PIXEL_ID'})// Then in your componentsfunctionComponent(){constmeta=useMetaPixel()meta.track('Purchase',{value: 99,currency: 'USD'})}

Pros: Can initialize outside components, useful for entry files like main.tsx

📝 TypeScript Support

Full type safety with exported types:

importtype{StandardEvent,EventData,EventMetaData,MetaPixelConfig}from'@adkit.so/meta-pixel-react'constconfig: MetaPixelConfig={pixelIds: 'YOUR_PIXEL_ID',debug: true}functiontrackEvent(event: StandardEvent,data: EventData){constmeta=useMetaPixel()meta.track(event,data)}

All methods, events, and parameters have complete TypeScript definitions with IntelliSense support in your IDE.

❓ Troubleshooting

Pixel not loading?

  1. Check your pixel ID - Make sure it's correct in your config
  2. Enable debug mode - Set debug={true} to see detailed logs
  3. Check browser console - Look for errors or warnings
  4. Check Ad Blockers - Ad blockers often block the Meta Pixel script
  5. Enable on localhost - Set enableLocalhost={true} for local testing

Hook error "must be used within MetaPixelProvider"?

Make sure your components are wrapped with MetaPixelProvider:

// ✅ Correct<MetaPixelProviderpixelIds="YOUR_PIXEL_ID"><Component/></MetaPixelProvider>// ❌ Wrong - Hook called outside Provider<Component/>

Events not showing in Meta Events Manager?

  • Wait a few minutes - Events can take 5-20 minutes to appear
  • Check Test Events - Use the Test Events tool in Meta Events Manager
  • Verify event names - Standard events are case-sensitive
  • Use event deduplication - Add unique eventID to prevent duplicates

TypeScript errors?

Make sure you have the latest version:

npm update @adkit.so/meta-pixel-react

Multiple pixels not working?

// ✅ Correct<MetaPixelProviderpixelIds={['ID_1','ID_2']}><App/></MetaPixelProvider>// ❌ Incorrect<MetaPixelProviderpixelIds="ID_1,ID_2"><App/></MetaPixelProvider>

📚 Official Documentation

Learn more about Meta Pixel from official Facebook resources:

🔗 Related Packages

📖 Full Guide

For a complete step-by-step guide on installing and configuring Meta Pixel, check out our detailed tutorial:

How to Install Meta Pixel

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

📄 License

MIT


Made with ❤️ by Adkit

If this package helped you, please consider giving it a ⭐️ on GitHub!

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages