UserFlux's React Native SDK - send your mobile app analytics data to the UserFlux platform.
- 📱 Cross-platform - Works on both iOS and Android
- 🔐 Privacy-focused - Anonymous ID and session management
- 📊 Auto-tracking - Automatic screen views and app lifecycle events
- 🔄 Offline support - Queue events when offline, send when connected
- 🎯 User identification - Link events to known users
- 📦 Batch processing - Efficient event batching and delivery
- 🔧 Device enrichment - Automatic device and app metadata
npm install @userflux/react-nativeor with Yarn:
yarn add @userflux/react-nativeThe SDK requires these peer dependencies:
npm install @react-native-async-storage/async-storage @react-native-community/netinfo react-native-device-infocd ios && pod installNo additional setup required for Android.
import UserFlux from '@userflux/react-native'
// Initialize as early as possible in your app (e.g., in App.js or index.js)
UserFlux.initialize('<YOUR_WRITE_KEY>', {
autoCapture: ['screen_views', 'app_opens'],
autoEnrich: true,
defaultTrackingProperties: {
environment: 'production',
app_name: 'MyApp'
},
trackSession: true
})The initialize method accepts the following options:
| Option | Type | Default | Description |
|---|---|---|---|
autoCapture |
Array<string> |
[] |
Events to automatically capture: 'screen_views', 'app_opens', 'all' |
autoEnrich |
boolean |
true |
Automatically enrich events with device and location data |
defaultTrackingProperties |
object |
{} |
Properties to include with every event |
trackSession |
boolean |
true |
Track sessions with unique identifiers |
disableUserIdStorage |
boolean |
false |
Don't persist user ID in AsyncStorage |
blockCommonBots |
boolean |
true |
Block tracking from emulators/simulators |
debugMode |
boolean |
false |
Enable debug logging |
// Track a custom event
await UserFlux.track({
event: 'purchase_completed',
properties: {
product_id: '12345',
product_name: 'Premium Subscription',
price: 9.99,
currency: 'USD'
}
})
// Track with user ID
await UserFlux.track({
event: 'button_clicked',
properties: {
button_name: 'checkout'
},
userId: 'user_123'
})// Identify a user with profile attributes
await UserFlux.identify({
userId: 'user_123',
properties: {
email: 'user@example.com',
name: 'John Doe',
subscription_plan: 'premium',
created_at: '2024-01-15'
}
})// Manual screen tracking
await UserFlux.trackScreenView('HomeScreen', {
category: 'main_navigation'
})
// Or integrate with React Navigation
import { NavigationContainer } from '@react-navigation/native'
function App() {
const navigationRef = useRef()
useEffect(() => {
UserFlux.setNavigationRef(navigationRef)
}, [])
return (
<NavigationContainer
ref={navigationRef}
onStateChange={async () => {
const currentScreen = navigationRef.current?.getCurrentRoute()?.name
if (currentScreen) {
await UserFlux.trackScreenView(currentScreen)
}
}}
>
{/* Your app screens */}
</NavigationContainer>
)
}For automatic screen tracking with React Navigation:
import { useNavigationContainerRef } from '@react-navigation/native'
function App() {
const navigationRef = useNavigationContainerRef()
const routeNameRef = useRef()
return (
<NavigationContainer
ref={navigationRef}
onReady={() => {
routeNameRef.current = navigationRef.getCurrentRoute().name
}}
onStateChange={async () => {
const previousRouteName = routeNameRef.current
const currentRouteName = navigationRef.getCurrentRoute().name
if (previousRouteName !== currentRouteName) {
await UserFlux.trackScreenView(currentRouteName, {
previous_screen: previousRouteName
})
}
routeNameRef.current = currentRouteName
}}
>
{/* Your navigation structure */}
</NavigationContainer>
)
}// Send multiple events at once
await UserFlux.trackBatch([
{
event: 'item_viewed',
properties: { item_id: '1', category: 'electronics' }
},
{
event: 'item_viewed',
properties: { item_id: '2', category: 'books' }
},
{
event: 'item_added_to_cart',
properties: { item_id: '1', quantity: 1 }
}
])Sessions are automatically managed with a 5-minute timeout. When the app goes to background and returns after 5 minutes, a new session is created.
// Get current session ID
const sessionId = UserFlux.getSessionId()
// Sessions automatically refresh on app foreground if expired// Set user ID (persisted across app launches)
UserFlux.setUserId('user_123')
// Set external ID (e.g., from your CRM)
UserFlux.setExternalId('crm_456')
// Get current user ID
const userId = UserFlux.getUserId()
// Get anonymous ID (device identifier)
const anonymousId = UserFlux.getAnonymousId()
// Reset user (logout)
await UserFlux.reset() // Clears user data and creates new anonymous IDUpdate default properties that are sent with every event:
UserFlux.updateDefaultTrackingProperties({
app_version: '2.0.0',
environment: 'production',
user_segment: 'premium'
})Events are automatically queued when the device is offline and sent when connectivity is restored:
// Events are queued automatically when offline
await UserFlux.track({
event: 'offline_action',
properties: { value: 100 }
})
// Manually flush the queue
await UserFlux.flush()Track app lifecycle events:
import { AppState } from 'react-native'
AppState.addEventListener('change', (nextAppState) => {
if (nextAppState === 'background') {
UserFlux.trackAppBackground()
} else if (nextAppState === 'active') {
UserFlux.trackAppOpen()
}
})The SDK automatically collects device information when autoEnrich is enabled:
- Platform (iOS/Android)
- Device model and brand
- OS version
- App version and build number
- Screen dimensions
- Timezone and locale
- Network carrier
- Memory and storage info
Track app opens from deep links:
import { Linking } from 'react-native'
Linking.getInitialURL().then(url => {
if (url) {
UserFlux.track({
event: 'app_opened_from_deep_link',
properties: {
url: url,
source: parseDeepLinkSource(url)
}
})
}
})The SDK includes TypeScript definitions:
import UserFlux, { TrackParameters, IdentifyParameters } from '@userflux/react-native'
const trackParams: TrackParameters = {
event: 'purchase',
properties: {
amount: 99.99
},
userId: 'user_123'
}
await UserFlux.track(trackParams)- Initialize Early: Call
UserFlux.initialize()as early as possible in your app lifecycle - User Identification: Call
identify()as soon as you have user information - Screen Tracking: Integrate with your navigation solution for automatic screen tracking
- Batch Events: Use
trackBatch()when tracking multiple related events - Cleanup: Call
UserFlux.cleanup()when your app unmounts (if needed)
- Check that you've initialized the SDK with a valid API key
- Verify network connectivity
- Enable debug mode to see logs:
{ debugMode: true } - Check that events are not being blocked by emulator detection
- The SDK uses AsyncStorage for persistence
- Ensure AsyncStorage is properly installed and linked
- Storage is automatically cleared on
reset()
- Sessions timeout after 5 minutes of inactivity
- New sessions are created when the app returns from background after timeout
- Session IDs are not persisted between app launches
initialize(apiKey, options)- Initialize the SDKidentify(parameters)- Identify a usertrack(parameters)- Track an eventtrackBatch(events)- Track multiple eventstrackScreenView(screenName, properties)- Track a screen viewreset()- Reset the SDK and clear dataflush()- Force flush pending events
setUserId(userId)- Set the user IDsetExternalId(externalId)- Set external IDgetUserId()- Get current user IDgetAnonymousId()- Get anonymous IDgetSessionId()- Get current session ID
updateDefaultTrackingProperties(properties)- Update default propertiessetNavigationRef(ref)- Set navigation reference for auto-trackingcleanup()- Clean up listeners and intervals
For issues, questions, or feature requests:
- GitHub Issues: https://github.com/userflux/react-native/issues
- Documentation: https://docs.userflux.com
- Support: support@userflux.com
ISC License - see LICENSE file for details