Purely built for React Native, this library allows 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.
Installation
In your React Native or Expo project add the posthog-react-native
package to your project as well as the required peer dependencies.
Expo Apps
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# ornpm i -s posthog-react-native @react-native-async-storage/async-storage react-native-device-info
Configuration
With the PosthogProvider
The recommended flow for setting up PostHog React Native is to use the PostHogProvider
which utilises the Context API to pass the PostHog Client around as well as enabling autocapture and ensuring that the queue is flushed at the right time:
Without the PosthogProvider
Due to the Async nature of React Native, PostHog needs to be initialised asynchronously in order for the persisted state to be loaded properly. The PosthogProvider
takes care of this under-the-hood but you can alternatively create the instance yourself like so:
// posthog.tsimport PostHog from 'posthog-react-native'export let posthog: PostHog | undefined = undefinedexport const posthogPromise: Promise<PostHog> = PostHog.initAsync('<ph_project_api_key>', {// PostHog API host (https://app.posthog.com by default)host: '<ph_instance_address>'})posthogPromise.then(client => {posthog = client})// app.tsimport { posthog, posthogPromise} from './posthog'export function MyApp1() {useEffect(() => {// Use posthog optionally with the possibility that it may still be loadingposthog?.capture('MyApp1 loaded')// OR use posthog via the promiseposthogPromise.then(ph => ph.capture('MyApp1 loaded')}, [])return <View>Your app code</View>}// You can even use this instance with the PostHogProviderexport function MyApp2() {return <PostHogProvider client={posthog}>{/* Your app code */}</PostHogProvider>}
Configuration options
For most people, the default configuration options will work great but if you need to you can further customise how PostHog will work.
export const posthog = await PostHog.initAsync("<ph_project_api_key>", {// PostHog API hosthost?: string = "https://app.posthog.com",// The number of events to queue before sending to PostHog (flushing)flushAt?: number = 20,// The interval in milliseconds between periodic flushesflushInterval?: number = 10000// If set to false, tracking will be disabled until `optIn` is calledenable?: boolean = true,// Whether to track that `getFeatureFlag` was called (used by Expriements)sendFeatureFlagEvent?: boolean = true,// Whether to load feature flags when initialised or notpreloadFeatureFlags?: boolean = true,// How many times we will retry HTTP requestsfetchRetryCount?: number = 3,// The delay between HTTP request retriesfetchRetryDelay?: number = 3000,// For Session Analysis how long before we expire a sessionsessionExpirationTimeSeconds?: number = 1800 // 30 mins// Whether to post events to PostHog in JSON or compressed formatcaptureMode?: 'json' | 'form'})
Usage
Autocapture
Autocapture tracks these events:
- Application Opened - once 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
- $screen - when the user navigates (if using @react-navigation/native)
- $autocapture - touch events when the user interacts with the screen
With Autocapture, all touch events for children of PosthogProvider
will be tracked, capturing a snapshot of the view hierarchy at that point. This allows you to create Insights in PostHog without having to add many custom events.
PostHog will try to generate a sensible name for the touched element based on the React component displayName
or name
but you can force this to something reliable (and also clearly marked for posthog tracking) using the ph-label
prop.
<View ph-label="my-special-label"></View>
If there are elements you don't want to be captured, you can add the ph-no-capture
property like so. If this property is found anywhere in the view hierarchy, the entire touch event is ignored.
<View ph-no-capture>Sensitive view here</View>
Basic usage:
// App.(js|ts)import {PostHogProvider} from 'posthog-react-native'import {NavigationContainer} from '@react-navigation/native';export function App() {return (<NavigationContainer><PostHogProvider apiKey="<ph_project_api_key>" autocapture>{/* Rest of app */}</PostHogProvider></NavigationContainer>)}
You can tweak how autocapture works by passing custom options.
<PostHogProvider apiKey="<ph_project_api_key>" autocapture={{captureTouches: true, // If you don't want to capture touch events set this to falsecaptureLifecycleEvents: true, // If you don't want to capture the Lifecycle Events (e.g. Application Opened) set this to falsecaptureScreens: true, // If you don't want to capture screen events set this to falseignoreLabels: [], // Any labels here will be ignored from the stack in touch eventscustomLabelProp: "ph-label",noCaptureProp: "ph-no-capture",navigation: {// By default only the Screen name is tracked but it is possible to track the// params or modify the name by intercepting theautocapture like sorouteToName: (name, params) => {if (params.id) return `${name}/${params.id}`return name},routeToParams: (name, params) => {if (name === "SensitiveScreen) return undefinedreturn params},}}}>...</PostHogProvider>
Identify
We highly recommend reading our section on Identifying users to better understand how to correctly use this method.
When you start tracking events with PostHog, each user gets an anonymous ID that is used to identify them in the system.
In order to link this anonymous user with someone from your database, use the identify
call.
Identify lets you add metadata on your users so you can more easily identify who they are in PostHog, and even do things like segment users by these properties.
An identify call requires:
distinctId
which uniquely identifies your user in your databaseuserProperties
with a dictionary with key: value pairs
posthog.identify('distinctID', {email: 'user@posthog.com',name: 'My Name'})
The most obvious place to make this call is whenever a user signs up, or when they update their information.
When you call identify
, all previously tracked anonymous events will be linked to the user.
Capture
Capture allows you to capture anything a user does within your system, which you can later use in PostHog to find patterns in usage, work out which features to improve or where people are giving up.
A capture
call requires:
event
to specify the event name- We recommend naming events with "[noun][verb]", such as
movie played
ormovie updated
, in order to easily identify what your events mean later on (we know this from experience).
- We recommend naming events with "[noun][verb]", such as
Optionally you can submit:
properties
, which is an object with any information you'd like to add
For example:
posthog.capture('Button B Clicked', {color: "blue",icon: "new2-final"})
Setting user properties via an event
When capturing an event, you can pass a property called $set
as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.
$set
Example
posthog.capture('some event', { $set: { userProperty: 'value' } })
Usage
When capturing an event, you can pass a property called $set
as an event property, and specify its value to be an object with properties to be set on the user that will be associated with the user who triggered the event.
$set_once
Example
posthog.capture('some event', { $set_once: { userProperty: 'value' } })
Usage
$set_once
works just like $set
, except that it will only set the property if the user doesn't already have that property set.
Super Properties
Super Properties are properties associated with events that are set once and then sent with every capture
call, be it a $screen, an autocaptured touch, or anything else.
They are set using posthog.register
, which takes a properties object as a parameter, and they persist across sessions.
For example, take a look at the following call:
posthog.register({'icecream pref': 'vanilla',team_id: 22,})
The call above ensures that every event sent by the user will include "icecream pref": "vanilla"
and "team_id": 22
. This way, if you filtered events by property using icecream_pref = vanilla
, it would display all events captured on that user after the posthog.register
call, since they all include the specified Super Property.
However, please note that this does not store properties against the User, only against their events. To store properties against the User object, you should use posthog.identify
. More information on this can be found on the Sending User Information section.
Removing stored Super Properties
Super Properties are persisted across sessions so you have to explicitly remove them if they are no longer relevant. In order to stop sending a Super Property with events, you can use posthog.unregister
, like so:
posthog.unregister('icecream pref'),
This will remove the Super Property and subsequent events will not include it.
If you are doing this as part of a user logging out you can instead simply use posthog.reset
which takes care of clearing all stored Super Properties and more.
Flush
You can set the number of events in the configuration that should queue before flushing.
Setting this to 1
will send events immediately and will use more battery. This is set to 20
by default.
You can also configure the flush interval. By default we flush all events after 30
seconds,
no matter how many events have gathered.
You can also manually flush the queue, like so:
posthog.flush()// or using async/awaitawait posthog.flushAsync()
Reset
To reset the user's ID and anonymous ID, call reset
. Usually you would do this right after the user logs out.
posthog.reset()
Opt in/out
By default, PostHog has tracking enabled unless it is forcefully disabled by default using the option { enable: false }
.
You can give your users the option to opt in or out by calling the relevant methods. Once these have been called they are persisted and will be respected until optIn/Out is called again or the reset
function is called.
To Opt in/out of tracking, use the following calls.
posthog.optIn() // opt inposthog.optOut() // opt out
If you still wish capture these events but want to create a distinction between users and team in PostHog, you should look into Cohorts.
Feature Flags
Feature Flags can be loaded directly or via a helpful hook
import { useFeatureFlag } from "posthog-react-native"const MyComponent = () => {const showFlaggedFeature = useFeatureFlag("my-flag-id")const multiVariantFeature = useFeatureFlag("my-multivariant-feature-flag-id")if (showFlaggedFeature === undefined) {// the response is undefined if the flags are being loadedreturn null}return showFlaggedFeature ? (<Text>Testing feature 😄</Text>) : (<Text>Not Testing feature 😢</Text>)}
Alternatively you can call load the feature flags directly:
// Defaults to undefined if not loaded yet or if there was a problem loadingposthog.getFeatureFlag("my-flag")// Multi variant feature flags are returned as a stringposthog.getFeatureFlag("my-multivariant-flag")
PostHog will load feature flags when instantiated and will refresh whenever other methods are called that could affect the flag such as .group()
. If you have the need to forcefully trigger the refresh however you can use reloadFeatureFlagsAsync
posthog.reloadFeatureFlagsAsync().then(refreshedFlags => console.log(refreshedFlags))
Bootstrapping Flags
There is a delay between loading the library and feature flags becoming available to use. For some cases, like redirecting users to a different page based on a feature flag, this is extremely detrimental, as the flags load after the redirect logic occurs, thus never working.
In cases like these, where you want flags to be immediately available on page load, you can use the bootstrap library option.
This allows you to pass in a distinctID and feature flags during library initialisation, like so:
const posthog = await Posthog.initAsync('<ph_project_api_key>', {host: 'https://app.posthog.com',bootstrap: {distinctID: 'your-anonymous-id',featureFlags: {'flag-1': true,'variant-flag': 'control','other-flag': false}}})
To compute these flag values, use the corresponding getAllFlags
method in your server-side library. Note that bootstrapping flags requires server-side initialisation.
If the ID you're passing in is an identified ID (that is, an ID with which you've called posthog.identify()
elsewhere), you can also pass in the isIdentifiedID
bootstrap option, which ensures that this ID is treated as an identified ID in the library. This is helpful as it warns you when you try to do something wrong with this ID, like calling identify
again.
const posthog = await Posthog.initAsync('<ph_project_api_key>', {host: 'https://app.posthog.com',bootstrap: {distinctID: 'your-identified-id',isIdentifiedID: true,featureFlags: {'flag-1': true,'variant-flag': 'control','other-flag': false}}})
Note: Passing in a distinctID to bootstrap replaces any existing IDs, which means you may fail to connect any old anonymous user events with the logged in person, if your logic calls identify in the frontend immediately on login. In this case, you can omit passing in the distinctID.
Group analytics
PostHog 1.31.0 introduced support for group analytics, which allows you to associate users and events with larger groups (teams, organizations, etc.).
Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more here.
- Make a group active and update properties
posthog.group('company', 'id:5', {company_name: 'Awesome Inc.',employees: 11,})
- Make a group active without updating properties
posthog.group('company', 'id:77')
Once a group has been made active, all subsequent events that are sent using the client will be associated with that group automatically.
Sending screen views
With the PostHogProvider
, screen tracking is automatically captured if the autocapture
property is used. Currently only @react-navigation/native is supported by autocapture and it is important that the PostHogProvider
is configured as a child of the NavigationContainer
as below:
See autocapture for configuration.
If you want to manually send a new screen capture event, use the screen
function. This function requires a name
. You may also pass in an optional properties
object.
posthog.screen('Dashboard', {background: 'blue',hero: 'superhog',})
Upgrading from V1 to V2
V1 of this library utilised the underlying posthog-ios
and posthog-android
SDKs to do most of the work. Since the new version is written entirely in JS, using only Expo supported libraries, there are some changes to the way PostHog is configured as well as actually calling PostHog.
For iOS, the new React Native SDK will attempt to migrate the previously persisted data which should result in no unexpected changes to tracked data.
For Android, it is unfortunately not possible for persisted Android data to be loaded which means stored information such as the randomly generated anonymousId
or the distinctId
set by posthog.identify
will not be present. For identified users, the simple workaround is to ensure that identify
is called at least once when the app loads. For anonymous users there is unfortunately no straightforward workaround they will show up as new anonymous users in PostHog.
// DEPRECATED V1 Setupimport PostHog from 'posthog-react-native'await PostHog.setup('phc_ChmcdLbC770zgl23gp3Lax6SERzC2szOUxtp0Uy4nTf', {host: 'https://app.posthog.com',captureApplicationLifecycleEvents: false, // Replaced by `PostHogProvider`captureDeepLinks: false, // No longer supportedrecordScreenViews: false, // Replaced by `PostHogProvider` supporting @react-navigation/nativeflushInterval: 30, // Stays the sameflushAt: 20, // Stays the sameandroid: {...}, // No longer needediOS: {...}, // No longer needed})PostHog.capture("foo")// V2 Setup differenceimport PostHog from 'posthog-react-native'const posthog = await Posthog.initAsync('phc_ChmcdLbC770zgl23gp3Lax6SERzC2szOUxtp0Uy4nTf', {host: 'https://app.posthog.com',// Add any other options here.})// Use created instance rather than the PostHog classposthog.capture("foo")