Implementing Analytics and Tracking
1. Setting Up Analytics SDK
Example: Installing and Configuring React Native Analytics
// Install the analytics SDK
// npm install @react-native-firebase/analytics
import analytics from '@react-native-firebase/analytics';
// Initialize analytics
analytics().setAnalyticsCollectionEnabled(true);
// Set user properties
analytics().setUserId('user123');
analytics().setUserProperty('accountType', 'premium');
| SDK | Installation Command | Key Features |
|---|---|---|
| Firebase Analytics | npm install @react-native-firebase/analytics |
Event tracking, user properties, screen reporting |
| Mixpanel | npm install mixpanel-react-native |
Advanced segmentation, funnel analysis, A/B testing |
| Amplitude | npm install amplitude-react-native |
User lifecycle, retention, cohort analysis |
Note: Firebase Analytics is the most commonly used analytics SDK for React Native apps, offering deep integration with Google's ecosystem.
2. Tracking Screen Views
| Property | Description | Example |
|---|---|---|
| screenName | Name of the screen being tracked | 'HomeScreen' |
| screenType | Type of screen (e.g., 'landing', 'product') | 'product' |
| userId | Unique identifier for the user | 'user_12345' |
Example: Tracking Screen View with React Native
import analytics from 'react-native-analytics';
const trackScreenView = () => {
analytics.trackScreenView({
screenName: 'HomeScreen',
screenType: 'landing',
userId: 'user_12345'
});
};
Note: Ensure screen names are consistent across your app to maintain accurate analytics.
3. Tracking User Events
| Event Type | Description | Properties | Usage Example |
|---|---|---|---|
| track | Tracks a user event with custom properties | event: string, properties?: object |
|
| identify | Associates a user with a unique identifier | userId: string, traits?: object |
|
| screen | Tracks screen views in the app | name: string, properties?: object |
|
Example: Tracking a Purchase Event
analytics.track('Purchase Completed', {
productId: 'prod_123',
amount: 29.99,
currency: 'USD',
category: 'Electronics'
})
Note: Make sure to initialize the analytics library before tracking any events.
Warning: Avoid tracking sensitive user data like passwords or PII.
4. Setting User Properties
| Property | Description | Values | Notes |
|---|---|---|---|
| userId | Unique identifier for the user | string |
Required for tracking user-specific events |
| userProperties | Object containing custom user properties | object |
Key-value pairs of user attributes |
Example: Setting User Properties
import analytics from 'react-native-analytics';
analytics.setUserId('user123');
analytics.setUserProperties({
age: 30,
location: 'New York',
isPremium: true
});
Note: User properties are persisted across sessions and can be used to segment users in analytics dashboards.
5. Implementing Custom Events
| Event Name | Properties | Description |
|---|---|---|
| custom.event.name | string |
Name of the custom event to be tracked |
| event.data | object |
Data associated with the event (optional) |
Example: Tracking Custom Event
import { Analytics } from 'react-native-analytics';
Analytics.trackEvent('custom.event.name', {
userId: '12345',
action: 'button_click'
});
Note: Ensure that event names follow a consistent naming convention to maintain clarity in analytics dashboards.
6. Tracking E-commerce Events
| Event Type | Description | Properties | Usage |
|---|---|---|---|
| productViewed | When a user views a product detail page | product_id, product_name, price |
Track engagement with specific products |
| productAddedToCart | When a user adds a product to their cart | product_id, quantity, cart_value |
Monitor cart additions and conversion funnel |
| purchaseCompleted | When a purchase is successfully completed | order_id, total_amount, items |
Measure revenue and transaction success |
Example: Tracking Product Viewed
import analytics from 'react-native-analytics';
analytics.track('productViewed', {
product_id: '12345',
product_name: 'Wireless Headphones',
price: 99.99
});
Example: Tracking Purchase Completed
analytics.track('purchaseCompleted', {
order_id: 'ORD-001',
total_amount: 299.97,
items: [
{ product_id: '12345', quantity: 2, price: 99.99 }
]
});
7. Using Event Parameters
| Parameter | Type | Description | Required |
|---|---|---|---|
| event | string |
Name of the event being tracked | Yes |
| parameters | object |
Additional data to associate with the event | No |
Example: Tracking an event with parameters
import analytics from 'react-native-analytics';
analytics.track('user_login', {
userId: '12345',
method: 'google',
timestamp: Date.now()
});
Note: Event parameters should be kept minimal to avoid performance issues and respect user privacy.
8. Implementing Conversion Tracking
| Feature | Description | Implementation |
|---|---|---|
| Event Tracking | Tracks user actions like button clicks or form submissions | import { logEvent } from 'expo-firebase-analytics';\n\nlogEvent('button_click', {\n button_name: 'submit_form'\n}); |
| Revenue Tracking | Tracks purchase events with monetary value | logEvent('purchase', {\n value: 29.99,\n currency: 'USD'\n}); |
| Custom Parameters | Allows adding custom data to events | logEvent('level_complete', {\n level: 'level_5',\n score: 95\n}); |
Example: Setting Up Conversion Tracking
import analytics from '@react-native-firebase/analytics';\n\n// Log a purchase event\nawait analytics().logPurchase({\n value: 10.99,\n currency: 'USD',\n item_id: 'item_123'\n});
Note: Ensure Firebase Analytics is properly configured in your project before implementing conversion tracking.
Warning: Do not log sensitive user data in conversion events.
9. Testing Analytics Implementation
Example: Testing with React Native Debugger
import { Platform } from 'react-native';
import Analytics from 'react-native-analytics';
// Mock analytics for testing
const mockAnalytics = {
trackEvent: (event, properties) => {
console.log(`[TEST] Event tracked: ${event}`, properties);
},
trackScreen: (screenName) => {
console.log(`[TEST] Screen tracked: ${screenName}`);
}
};
// Use mock in test environment
const analytics = Platform.OS === 'test' ? mockAnalytics : Analytics;
export default analytics;
| Method | Description | Parameters | Notes |
|---|---|---|---|
| trackEvent | Tracks a custom event with properties | eventName: string, properties?: object |
Use for user actions like button taps or form submissions |
| trackScreen | Tracks screen view changes | screenName: string |
Automatically sent when using react-navigation |
| setUserProperties | Sets user-level properties for segmentation | properties: object |
Can include userId, email, or custom traits |
Testing Workflow
- Set up a test environment with mocked analytics
- Use
console.logor a test logging service to capture events - Run unit tests with
jestordetox - Verify event payloads match expected structure
- Check that analytics are not sent in test mode
Note: Use environment variables to toggle between real and mock analytics in different build configurations.
Warning: Never send real analytics data in test builds. Always mock or disable tracking in development and test environments.
10. Analyzing User Behavior
| Event | Description | Parameters | Usage |
|---|---|---|---|
| screen_view | Tracks when a user views a screen | screen_name, screen_class |
Use to analyze screen flow and engagement |
| user_engagement | Tracks time spent on a screen | engagement_time_msec, screen_name |
Measure user retention and interest |
| custom_event | Tracks custom user actions | event_name, param1, param2 |
Track specific user interactions or goals |
Example: Tracking Screen Views
import analytics from 'react-native-firebase/analytics';
analytics().logScreenView({
screen_name: 'HomeScreen',
screen_class: 'com.example.HomeScreen'
});
Example: Tracking Custom Events
analytics().logEvent('purchase', {
item_name: 'Premium Subscription',
price: 9.99,
currency: 'USD'
});
Note: Firebase Analytics is the most commonly used analytics service for React Native apps.