@analytics-v0/react
v1.0.5
Published
Simple and lightweight analytics tracking for React applications
Maintainers
Readme
@analytics-v0/react
A lightweight, privacy-focused analytics tracking library for React applications.
Features
- 📦 Lightweight and easy to integrate
- ⚡ Automatic page view tracking
- 🎯 Custom event tracking
- 🔄 Session management
- 📊 Batched event sending
- 📱 Device and browser information
- 🔍 Debug mode for development
- 📝 TypeScript support
Installation
npm install @analytics-v0/react
# or
yarn add @analytics-v0/reactQuick Start
- Wrap your application with the
AnalyticsProvider:
import { AnalyticsProvider } from '@analytics-v0/react';
function App() {
return (
<AnalyticsProvider
config={{
projectId: 'your-project-id',
// Optional configurations
apiEndpoint: 'https://your-api.com/v1',
debug: true,
batchSize: 10,
batchInterval: 5000,
}}
>
<YourApp />
</AnalyticsProvider>
);
}- Use the
useAnalyticshook in your components:
import { useAnalytics } from '@analytics-v0/react';
function CheckoutButton() {
const analytics = useAnalytics();
const handleCheckout = () => {
analytics.track('checkout_started', {
cartValue: 99.99,
currency: 'USD',
items: 3
});
// ... handle checkout logic
};
return <button onClick={handleCheckout}>Checkout</button>;
}API Reference
AnalyticsProvider
The provider component that initializes the analytics system.
Props
interface AnalyticsConfig {
projectId: string;
apiEndpoint?: string;
debug?: boolean;
batchSize?: number;
batchInterval?: number;
disabled?: boolean;
}projectId(required): Your project's unique identifierapiEndpoint(optional): Custom API endpoint for sending eventsdebug(optional): Enable debug loggingbatchSize(optional): Number of events to batch before sending (default: 10)batchInterval(optional): Maximum time to wait before sending batched events in ms (default: 5000)disabled(optional): Disable all tracking when true
useAnalytics Hook
The main hook for tracking events.
Methods
track(name: string, properties?: Record<string, any>)
Track custom events with optional properties.
const analytics = useAnalytics();
// Basic event
analytics.track('button_click');
// Event with properties
analytics.track('product_view', {
productId: '123',
category: 'Electronics',
price: 299.99
});pageView(path: string, properties?: Record<string, any>)
Manually track page views (automatic in most cases).
const analytics = useAnalytics();
// Track custom page view
analytics.pageView('/products/123', {
category: 'Products',
searchQuery: 'phones'
});identify(userId: string, traits?: Record<string, any>)
Associate events with a user identity.
const analytics = useAnalytics();
// Identify a user
analytics.identify('user123', {
email: '[email protected]',
plan: 'premium',
signupDate: '2023-01-01'
});Advanced Usage
Configuration Options
The AnalyticsProvider accepts the following configuration options:
interface AnalyticsConfig {
projectId: string; // Required: Your project identifier
apiEndpoint?: string; // Optional: Custom API endpoint (default: 'https://api.analytics-v0.com')
debug?: boolean; // Optional: Enable debug logging (default: false)
batchSize?: number; // Optional: Number of events to batch before sending (default: 10)
batchInterval?: number; // Optional: Interval in ms to send batched events (default: 5000)
disabled?: boolean; // Optional: Disable all tracking (default: false)
}Event Tracking API
The useAnalytics hook provides the following methods:
track(name: string, properties?: Record<string, any>)
Track custom events with optional properties:
const { track } = useAnalytics();
// Basic event
track('button_click');
// Event with properties
track('purchase_complete', {
productId: '123',
price: 99.99,
currency: 'USD'
});pageView(path: string, properties?: Record<string, any>)
Track page views manually (automatic tracking is enabled by default):
const { pageView } = useAnalytics();
// Track current page
pageView(window.location.pathname);
// Track with custom properties
pageView('/checkout', {
referrer: document.referrer,
title: document.title
});Session Management
Sessions are automatically managed with the following behavior:
- New session created on first visit
- Session refreshed on activity
- Session expires after 30 minutes of inactivity
Browser Support
- Chrome, Firefox, Safari, Edge (latest 2 versions)
- IE11 with appropriate polyfills
TypeScript Support
For better TypeScript support, you can extend the default event properties:
declare module '@analytics-v0/react' {
interface CustomEventProperties {
productId?: string;
price?: number;
category?: string;
// Add your custom properties here
}
}Error Handling
The library includes built-in error handling and will:
- Retry failed network requests
- Queue events when offline
- Sync queued events when back online
Performance Considerations
- Lightweight bundle size (~4KB gzipped)
- Batched network requests
- Debounced event processing
- No external dependencies
Security
- HTTPS-only API endpoints
- No PII collected by default
- Data encryption in transit
- Configurable data retention
Automatic Data Collection
The library automatically collects the following information:
- Page views
- Session data
- Browser information
- Screen dimensions
- User timezone
- User language
- Referrer information
Example: E-commerce Implementation
import { useAnalytics } from '@analytics-v0/react';
function ProductPage({ product }) {
const analytics = useAnalytics();
useEffect(() => {
// Track product view
analytics.track('product_view', {
productId: product.id,
name: product.name,
price: product.price,
category: product.category
});
}, [product]);
const handleAddToCart = () => {
analytics.track('add_to_cart', {
productId: product.id,
name: product.name,
price: product.price,
quantity: 1
});
};
return (
<div>
<h1>{product.name}</h1>
<p>{product.description}</p>
<button onClick={handleAddToCart}>Add to Cart</button>
</div>
);
}Best Practices
Event Naming
- Use snake_case for event names
- Be consistent with naming conventions
- Use descriptive names (e.g., 'checkout_started' vs 'checkout')
Properties
- Include relevant context in properties
- Don't include sensitive information
- Keep property names consistent across events
User Identification
- Call identify() after user authentication
- Include relevant user traits
- Don't include personal identifiable information (PII) unless necessary
Performance
- Events are automatically batched
- Use the disabled prop in development/testing
- Monitor debug logs in development
Contributing
We welcome contributions! Please see our Contributing Guide for details.
License
MIT License - see LICENSE file for details
