references/react-native.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
React Native
Canonical URL: https://posthog.com/docs/libraries/react-native
On this page
- Install with the wizard
- Installation
- Capturing events
- Autocapture
- Common before_send patterns
- Identifying users
- Get the current user's distinct ID
- Alias
- Setting person properties
- Super properties
- Opt out of data capture
- Flush
- Reset after logout
- Offline behavior
- Opt in/out
- Feature Flags
- Experiments (A/B tests)
- Group analytics
- Error tracking
- Logs
- Session replay
- Surveys
- Push notifications
- Debug mode
- Disabling for local development
- Upgrading from V1, V2 to V3 or V3 to V4
Install with the wizard
Run this command in your project directory to add PostHog to your React Native project. The wizard detects your framework, installs the SDK, and sets up your first events.
npx @posthog/wizard
Or set it up manually by following the rest of this guide.
Installation
Our React Native enables you to integrate PostHog with your React Native project. For React Native projects built with Expo, there are no mobile native dependencies outside of supported Expo packages.
To install, add the posthog-react-native package to your project as well as the required peer dependencies.
Expo apps
npx expo install posthog-react-native expo-file-system expo-application expo-device expo-localization
React Native apps
yarn add posthog-react-native @react-native-async-storage/async-storage react-native-device-info react-native-localize
# or
npm i -s posthog-react-native @react-native-async-storage/async-storage react-native-device-info react-native-localize
React Native Web and macOS
If you're using React Native Web or React Native macOS, do not use the expo-file-system package since the Web and macOS targets aren't supported, use the @react-native-async-storage/async-storage package instead.
Configuration
With the PosthogProvider
The recommended way to set up PostHog for React Native is to use the PostHogProvider. This utilizes the Context API to pass the PostHog client around, and enables autocapture.
To set up PostHogProvider, add it to your App.js or App.ts file:
App.js
// App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
...
export function MyApp() {
return (
<PostHogProvider apiKey="<ph_project_token>" options={{
// usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
host: 'https://us.i.posthog.com',
}}>
<MyComponent />
</PostHogProvider>
)
}
Then you can access PostHog using the usePostHog() hook:
const MyComponent = () => {
const posthog = usePostHog()
useEffect(() => {
posthog.capture("event_name")
}, [posthog])
}
Without the PosthogProvider
If you prefer not to use the provider, you can initialize PostHog in its own file and import the instance from there:
posthog.ts
import PostHog from 'posthog-react-native'
export const posthog = new PostHog('<ph_project_token>', {
// usually 'https://us.i.posthog.com' or 'https://eu.i.posthog.com'
host: 'https://us.i.posthog.com'
})
Then you can access PostHog by importing your instance:
import { posthog } from './posthog'
export function MyApp1() {
useEffect(() => {
posthog.capture('event_name')
}, [])
return <View>Your app code</View>
}
You can even use this instance with the PostHogProvider:
import { posthog } from './posthog'
export function MyApp() {
return <PostHogProvider client={posthog}>{/* Your app code */}</PostHogProvider>
}
Choose an iOS dependency path for the native plugin
The optional @posthog/react-native-plugin package adds native features such as session replay and native crash capture. Install it as described in the guide for the feature that you use. Then choose one iOS dependency path:
| Path | Requirements | What it resolves |
| --- | --- | --- |
| CocoaPods | A React Native project that uses CocoaPods | CocoaPods resolves the plugin and posthog-ios. This remains the default path. |
| CocoaPods with posthog-ios through Swift Package Manager | React Native 0.75 or later and a CocoaPods project with dynamic frameworks | CocoaPods resolves the plugin. Swift Package Manager resolves posthog-ios. |
| Full Swift Package Manager | Verified with an iOS-only React Native 0.87.1 app and React Native Community CLI 20.2.0. Requires @posthog/react-native-plugin 2.4.0 or later, Xcode 16 or later, and an iOS 15.1 or later app deployment target. | React Native's experimental Swift Package Manager integration resolves the plugin and posthog-ios. This path does not use CocoaPods. |
This verification does not cover Expo or other React Native versions. Use CocoaPods or the hybrid path unless you validate the full Swift Package Manager path for your configuration.
CocoaPods
Use the standard React Native CocoaPods flow:
cd ios
pod install
The plugin podspec adds posthog-ios as a CocoaPods dependency. You do not need to add posthog-ios separately.
CocoaPods with posthog-ios through Swift Package Manager
Add the following property to ios/Podfile.properties.json:
{
"posthog.useSpm": "true"
}
Add dynamic frameworks to your ios/Podfile:
use_frameworks! :linkage => :dynamic
Then install the pods:
cd ios
pod install
This setting changes only how the plugin resolves posthog-ios. The plugin and other React Native dependencies still use CocoaPods.
Full Swift Package Manager
This path uses React Native's experimental CocoaPods-free iOS integration. Every native dependency in your app must support React Native's full Swift Package Manager integration. Use CocoaPods or the hybrid path if a dependency does not support it.
Install your JavaScript dependencies first. Make a clean commit or a backup of your iOS project before the conversion. Then run this command from the ios directory:
npx react-native spm add --deintegrate --yes
The --deintegrate option removes the complete CocoaPods integration from the iOS project. React Native then finds the plugin's ios/Package.swift manifest. Swift Package Manager resolves the plugin and posthog-ios. Do not run pod install for this path.
PostHog CI verifies this path with the configuration in the requirements table. The verified app sets its deployment target to iOS 15.1. The plugin package manifest has a separate iOS 15 minimum. The CocoaPods and hybrid paths keep the plugin podspec's iOS 13 minimum.
Set up a reverse proxy (recommended)
We recommend setting up a reverse proxy, so that events are less likely to be intercepted by tracking blockers.
We have our own managed reverse proxy service, which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy.
If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using Cloudflare, AWS Cloudfront, and Vercel.
Grouping products in one project (recommended)
If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and group them in one project.
This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms.
Add IPs to Firewall/WAF allowlists (recommended)
For certain features like heatmaps, your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site.
EU: 3.75.65.221, 18.197.246.42, 3.120.223.253
US: 44.205.89.55, 52.4.194.122, 44.208.188.173
These are public, stable IPs used by PostHog services.
PostHog captures heatmap screenshots using Browserless, which has its own IP addresses. Browserless publishes the current list here.
An allowlist does not help when your app has a private address. For apps on an internal network, see internal and intranet applications.
Configuration options
You can further customize how PostHog works through its configuration on initialization.
| Attribute | Description |
| --- | --- |
| host Type: String Default: https://us.i.posthog.com | PostHog API host (usually https://us.i.posthog.com by default or https://eu.i.posthog.com). Host is optional if you use https://us.i.posthog.com. |
| flushAt Type: Number Default: 20 | The number of events to queue before sending to PostHog (flushing). |
| flushInterval Type: Number Default: 10000 | The interval in milliseconds between periodic flushes. |
| maxBatchSize Type: Number Default: 100 | The maximum number of queued messages to be flushed as part of a single batch (must be higher than flushAt). |
| maxQueueSize Type: Number Default: 1000 | The maximum number of cached messages either in memory or on the local storage (must be higher than flushAt). |
| disabled Type: Boolean Default: false | If set to true, the SDK is essentially disabled (useful for local environments where you don't want to track anything). |
| defaultOptIn Type: Boolean Default: true | If set to false, the SDK will not track until the optIn() function is called. |
| sendFeatureFlagEvent Type: Boolean Default: true | Whether to track that getFeatureFlag was called (used by experiments). |
| preloadFeatureFlags Type: Boolean Default: true | Whether to load feature flags when initialized or not. |
| bootstrap Type: Object Default: {} | Seeds identity (distinctId, isIdentifiedId) and feature flag state (featureFlags, featureFlagPayloads) during initialization. See SDK bootstrapping. |
| disableRemoteFeatureFlags Type: Boolean Default: false | When true, the SDK never fetches or evaluates feature flags from PostHog, and identify(), group(), and reset() stop triggering /flags requests. Supply flag values yourself via bootstrap (at startup) and updateFlags() (at runtime). Available in version 4.49.0+. |
| fetchRetryCount Type: Number Default: 3 | How many times HTTP requests will be retried. |
| fetchRetryDelay Type: Number Default: 3000 | The delay between HTTP request retries. |
| requestTimeout Type: Number Default: 10000 | Timeout in milliseconds for any calls. |
| featureFlagsRequestTimeoutMs Type: Number Default: 10000 | Timeout in milliseconds for feature flag calls. |
| sessionExpirationTimeSeconds Type: Number Default: 1800 | For session analysis, how long before a session expires (defaults to 30 minutes). |
| persistence Type: String Default: file | Allows you to provide the storage type. file will try to load the best available storage, the provided customStorage, customAsyncStorage, or in-memory storage. |
| customAppProperties Type: Object or Function Default: null | Allows you to provide your own implementation of the common information about your App or a function to modify the default App properties generated. |
| customStorage Type: Object Default: null | Allows you to provide a custom asynchronous storage such as async-storage, expo-file-system, or a synchronous storage such as mmkv. If not provided, PostHog will attempt to use the best available storage via optional peer dependencies. If persistence is set to memory, this option is ignored. |
| captureAppLifecycleEvents Type: Boolean Default: true | Captures app lifecycle events such as Application Installed, Application Updated, Application Opened, Application Became Active, and Application Backgrounded. Enabled by default since version 4.39.0. |
| disableGeoip Type: Boolean Default: false | When true, disables automatic GeoIP resolution for events and feature flags. |
| enableSessionReplay Type: Boolean Default: false | Enable Recording of Session replay for Android and iOS. |
| sessionReplayConfig Type: Object Default: null | Session replay configuration. See the replay install docs for more details. |
| enablePersistSessionIdAcrossRestart Type: Boolean Default: false | When true, persists the $session_id across app restarts. If false, $session_id always resets on app restart. |
| evaluationContexts Type: Array of Strings Default: undefined | Evaluation context tags that constrain which feature flags are evaluated. When set, only flags with matching evaluation context tags (or no evaluation context tags) will be returned. This helps reduce unnecessary flag evaluations and improves performance. See evaluation contexts documentation for more details. Available in version 4.21.0+. The legacy parameter evaluationEnvironments (version 4.10.0+) is also supported for backward compatibility. |
| addTracingHeaders Type: Array of Strings Default: undefined | Hostnames for which PostHog should add tracing headers to outgoing fetch requests. Matching requests include X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID, which lets backend events, errors, and LLM traces link back to frontend sessions and replays. Use hostnames only, without the protocol or path. |
| before_send Type: Function Default: undefined | A callback function that is called before each event is sent to PostHog. You can use it to modify, filter, or suppress events. Return null to drop the event, or return the modified event to send it. See customizing exception capture for details. |
| capturePushNotificationSubscriptions Type: Boolean Default: true | Whether to automatically register this device's push token so Workflows can target it. Requires @posthog/react-native-plugin. See push notifications. Available in version 4.62.0+. |
| capturePushNotificationOpened Type: Boolean Default: true | Whether to automatically capture $push_notification_opened when the user taps a push notification. Requires @posthog/react-native-plugin. See push notifications. Available in version 4.62.0+. |
| pushIdentityProvider Type: Function Default: undefined | Supplies a signed identity-verification token for push subscription requests. Only needed when your push channel requires identity verification. See identity verification. Available in version 4.62.0+. |
Tracing headers
Use addTracingHeaders to connect React Native network requests to backend events, errors, and LLM traces captured by a server-side PostHog SDK:
const posthog = new PostHog('<ph_project_token>', {
host: 'https://us.i.posthog.com',
addTracingHeaders: ['api.example.com'],
})
Hostnames are matched exactly. The SDK patches global fetch and sends X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID on matching requests when those values are available.
Capturing events
You can send custom events using capture:
posthog.capture('user_signed_up')
Tip: We recommend using a
[object] [verb]format for your event names, where[object]is the entity that the behavior relates to, and[verb]is the behavior itself. For example,project created,user signed up, orinvite sent.
Setting event properties
Optionally, you can include additional information with the event by including a properties object:
posthog.capture('user_signed_up', {
login_type: "email",
is_free_trial: true
})
Capturing screen views
With @react-navigation/native and autocapture:
When using @react-navigation/native v6 or lower, screen tracking is automatically captured if the autocapture property is used in the PostHogProvider:
It is important that the PostHogProvider is configured as a child of the NavigationContainer:
// App.(js|ts)
import { PostHogProvider } from 'posthog-react-native'
import { NavigationContainer } from '@react-navigation/native'
export function App() {
return (
<NavigationContainer>
<PostHogProvider apiKey="<ph_project_token>" autocapture>
{/* Rest of app */}
</PostHogProvider>
</NavigationContainer>
)
}
When using @react-navigation/native v7 or higher, screen tracking has to be manually captured:
// App.(js|ts)
import { PostHogProvider } from 'posthog-react-native'
import { NavigationContainer } from '@react-navigation/native'
// Using `PostHogProvider` is optional, but needed if you want to capture touch events automatically with the `captureTouches` option.
export function App() {
return (
<NavigationContainer>
<PostHogProvider apiKey="<ph_project_token>" autocapture={{
captureScreens: false, // Screen events are handled differently for v7 and higher
captureTouches: true,
}}>
{/* Rest of app */}
</PostHogProvider>
</NavigationContainer>
)
}
Check out and set it up the official way for Screen tracking for analytics.
Then call the screen method within the trackScreenView method.
const posthog = usePostHog() // use the usePostHog hook if using the PostHogProvider or your own custom posthog instance
// you can read the params from `getCurrentRoute()`
posthog.screen(currentRouteName, params)
With react-native-navigation and autocapture:
First, simplify the wrapping of your screens with a shared PostHogProvider:
import PostHog, { PostHogProvider } from 'posthog-react-native'
import { Navigation } from 'react-native-navigation';
export const posthog = new PostHog('<ph_project_token>');
export const SharedPostHogProvider = (props: any) => {
return (
<PostHogProvider client={posthog} autocapture={{
captureScreens: false, // Screen events are handled differently for react-native-navigation
captureTouches: true,
}}>
{props.children}
</PostHogProvider>
);
};
Then, every screen needs to be wrapped with this provider if you want to capture touches or use the usePostHog() hook
export const MyScreen = () => {
return (
<SharedPostHogProvider>
<View>
...
</View>
</SharedPostHogProvider>
);
};
Navigation.registerComponent('Screen', () => MyScreen);
Navigation.events().registerAppLaunchedListener(async () => {
posthog.initReactNativeNavigation({
navigation: {
// (Optional) Set the name based on the route. Defaults to the route name.
routeToName: (name, properties) => name,
// (Optional) Tracks all passProps as properties. Defaults to undefined
routeToProperties: (name, properties) => properties,
},
captureScreens: true,
});
});
With expo-router:
Check out and set it up the official way for Screen tracking for analytics.
Then call the screen method within the useEffect callback.
const posthog = usePostHog() // use the usePostHog hook if using the PostHogProvider or your own custom posthog instance
posthog.screen(pathname, params)
Manually capturing screen capture events
If you prefer not to use autocapture, you can manually capture screen views by calling posthog.screen(). This function requires a name. You may also pass in an optional properties object.
posthog.screen('dashboard', {
background: 'blue',
hero: 'superhog',
})
Autocapture
PostHog autocapture can automatically track the following events for you:
- Application Opened – when the app is opened from a closed state
- Application Became Active – when the app comes to the foreground (e.g. from the app switcher)
- Application Backgrounded – when the app is sent to the background by the user
- Application Installed – when the app is installed.
- Application Updated – when the app is updated.
- $screen – when the user navigates (if using
@react-navigation/native(v6 or lower) orreact-native-navigation), check out the capturing screen views section - $autocapture – touch events when the user interacts with the screen
- $exception – when the app throws exceptions.
⚠️ React Navigation v7 users
React Navigation v7 restricts navigation hooks (such as
useNavigationState) to components rendered inside a Screen that belongs to a Navigator.Because of this change, automatic screen tracking may throw errors if PostHog is initialized outside a screen context. This commonly affects apps upgrading from React Navigation v6 to v7.
For React Navigation v7, we recommend disabling automatic screen capture for screens and manually calling
posthog.screen()inside each screen component. See the Capturing screen views section below.
Application lifecycle events are enabled by default. Screen capture is enabled by default in PostHogProvider unless you set captureScreens: false. Touch capture is disabled by default and requires captureTouches: true.
When touch capture is enabled, touch events for children of PostHogProvider are tracked, capturing a snapshot of the view hierarchy at that point. This enables you to create insights in PostHog without adding custom events.
PostHog will try to generate a sensible name for touched e