React SDK
React hooks and components for Entrolytics
React SDK
The @entrolytics/react-sdk package provides React hooks and components for tracking analytics in any React application.
Installation
pnpm add @entrolytics/react-sdkQuick Start
Add Provider
Wrap your app with EntrolyticsProvider:
import { EntrolyticsProvider } from '@entrolytics/react-sdk'
function App() {
return (
<EntrolyticsProvider
websiteId={import.meta.env.VITE_ENTROLYTICS_WEBSITE_ID}
host={import.meta.env.VITE_ENTROLYTICS_HOST}
autoTrack={true}
>
<YourApp />
</EntrolyticsProvider>
)
}Add Environment Variables
Create a .env file:
VITE_ENTROLYTICS_WEBSITE_ID=your-website-id
VITE_ENTROLYTICS_HOST=https://entrolytics.devTrack Events
Use the useEntrolytics hook:
import { useEntrolytics } from '@entrolytics/react-sdk'
function SignupButton() {
const { track } = useEntrolytics()
return (
<button onClick={() => track('signup', { plan: 'pro' })}>Sign Up</button>
)
}Configuration
interface EntrolyticsConfig {
websiteId?: string
linkId?: string
pixelId?: string
host?: string
autoTrack?: boolean
useEdgeRuntime?: boolean // Use edge-optimized endpoints (default: true)
tag?: string
domains?: string[]
excludeSearch?: boolean
excludeHash?: boolean
respectDoNotTrack?: boolean
ignoreLocalhost?: boolean
beforeSend?: BeforeSendCallback
trackOutboundLinks?: boolean
proxy?: ProxyConfig | false
debug?: boolean
}Runtime Configuration
The useEdgeRuntime prop controls which collection endpoint is used:
Edge Runtime (default) - Optimized for speed and global distribution:
<EntrolyticsProvider
websiteId='your-website-id'
useEdgeRuntime={true} // or omit (default)
>
<App />
</EntrolyticsProvider>- Latency: Sub-50ms response times globally
- Best for: Production apps, globally distributed users
- Endpoint: Uses
/api/send-nativefor edge-to-edge communication - Limitations: No ClickHouse export, basic geo data
Node.js Runtime - Full-featured with advanced capabilities:
<EntrolyticsProvider websiteId='your-website-id' useEdgeRuntime={false}>
<App />
</EntrolyticsProvider>- Features: ClickHouse export, MaxMind GeoIP (city-level accuracy)
- Best for: Self-hosted deployments, advanced analytics requirements
- Endpoint: Uses
/api/sendfor Node.js runtime - Latency: 50-150ms (regional)
When to use Node.js runtime:
- Self-hosted deployments without edge runtime support
- Applications requiring ClickHouse data export
- Need for advanced geo-targeting with MaxMind
- Custom server-side analytics workflows
See the Intelligent Routing guide for more details on collection endpoints.
Hooks
useEntrolytics
Main hook providing all tracking methods:
const {
track,
trackView,
identify,
trackRevenue,
trackOutboundLink,
setTag,
isReady,
isEnabled
} = useEntrolytics()useTrackPageView
Automatically track page views:
import { useTrackPageView } from '@entrolytics/react-sdk'
function Page() {
useTrackPageView() // Auto-track on mount and route changes
}useTrackEvent
Create a reusable event tracker:
import { useTrackEvent } from '@entrolytics/react-sdk'
function ProductCard({ product }) {
const trackEvent = useTrackEvent()
return (
<button
onClick={() => trackEvent('add_to_cart', { productId: product.id })}
>
Add to Cart
</button>
)
}useTrackOutboundLink
Track external link clicks:
import { useTrackOutboundLink } from '@entrolytics/react-sdk'
function ExternalLinks() {
const trackOutboundLink = useTrackOutboundLink()
return (
<a
href='https://example.com'
onClick={() => trackOutboundLink('https://example.com')}
>
External Link
</a>
)
}useTrackRevenue
Track revenue events:
import { useTrackRevenue } from '@entrolytics/react-sdk'
function CheckoutButton({ amount }) {
const trackRevenue = useTrackRevenue()
const handleCheckout = async () => {
await processPayment()
trackRevenue('purchase', amount, 'USD')
}
return <button onClick={handleCheckout}>Pay ${amount}</button>
}useIdentify
Identify users:
import { useIdentify } from '@entrolytics/react-sdk'
function UserProfile({ user }) {
const identify = useIdentify()
useEffect(() => {
identify(user.id, { email: user.email, plan: user.plan })
}, [user])
return <div>Welcome, {user.name}!</div>
}useWebVitals (Phase 2)
Automatically track Core Web Vitals (LCP, FID, CLS, FCP, TTFB, INP):
import { useWebVitals } from '@entrolytics/react-sdk'
function App() {
// Basic usage - automatically reports all Web Vitals
useWebVitals()
return <YourApp />
}
function AppWithOptions() {
// Advanced usage with options
useWebVitals({
// Optional: only track specific metrics
metrics: ['LCP', 'CLS', 'INP'],
// Optional: callback for each vital measurement
onVital: (metric) => {
console.log(`${metric.name}: ${metric.value} (${metric.rating})`)
},
// Optional: disable vitals tracking
enabled: true
})
return <YourApp />
}Note: Requires the optional web-vitals peer dependency:
pnpm add web-vitalsuseFormTracking (Phase 2)
Automatically track form interactions and conversions:
import { useFormTracking } from '@entrolytics/react-sdk'
function ContactForm() {
const formRef = useFormTracking({
formId: 'contact-form',
// Optional: track specific events
trackFocus: true,
trackBlur: true,
trackChange: true,
trackSubmit: true,
trackAbandonment: true
})
return (
<form ref={formRef}>
<input name='email' type='email' placeholder='Email' />
<input name='message' type='text' placeholder='Message' />
<button type='submit'>Send</button>
</form>
)
}Form Events Tracked:
- focus - When a user focuses on a form field
- blur - When a user leaves a form field (includes time spent)
- change - When a field value changes
- submit - When the form is submitted
- abandon - When a user leaves the page with an incomplete form
Components
TrackEvent
import { TrackEvent } from '@entrolytics/react-sdk'
;<TrackEvent name='cta-click' data={{ location: 'hero' }}>
<button>Click Me</button>
</TrackEvent>OutboundLink
import { OutboundLink } from '@entrolytics/react-sdk'
;<OutboundLink href='https://example.com'>External Link</OutboundLink>Framework Examples
Vite + React
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { EntrolyticsProvider } from '@entrolytics/react-sdk'
import App from './App'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<EntrolyticsProvider
websiteId={import.meta.env.VITE_ENTROLYTICS_WEBSITE_ID}
>
<App />
</EntrolyticsProvider>
</StrictMode>
)React Router
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { useEntrolytics } from '@entrolytics/react-sdk'
function RouteTracker() {
const location = useLocation()
const { trackView } = useEntrolytics()
useEffect(() => {
trackView(location.pathname + location.search)
}, [location, trackView])
return null
}
// Add to your app
;<RouteTracker />Features
- ✅ React 18+ support
- ✅ Provider-based configuration
- ✅ Hooks for all tracking methods
- ✅ Declarative event components
- ✅ Automatic page view tracking
- ✅ Link and pixel tracking support
- ✅ TypeScript-first with full type safety
- ✅ Web Vitals tracking (LCP, FID, CLS, FCP, TTFB, INP)
- ✅ Form analytics (focus, blur, submit, abandonment)
- ✅ Works with any React framework (Vite, CRA, etc.)
Support
- GitHub Issues
- Email: hey@entrolytics.dev