React Native

Last updated:

Which features are available in this library?
  • Event capture
  • Autocapture
  • User identification
  • Session recording
  • Feature flags
  • Group analytics

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

sh
expo install posthog-react-native expo-file-system expo-application expo-device expo-localization

React Native Apps

sh
yarn add posthog-react-native @react-native-async-storage/async-storage react-native-device-info
# or
npm 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:

JSX
// App.(js|ts)
import { usePostHog, PostHogProvider } from 'posthog-react-native'
...
export function MyApp() {
return (
<PostHogProvider apiKey="<ph_project_api_key>" options={{
// (Optional) PostHog API host (https://app.posthog.com by default)
host: '<ph_instance_address>',
}}>
<MyComponent />
</PostHogProvider>
)
}
// Now you can simply access posthog elsewhere in the app like so
const MyComponent = () => {
const posthog = usePostHog()
useEffect(() => {
posthog.capture("MyComponent loaded", { foo: "bar" })
}, [])
}

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:

TSX
// posthog.ts
import PostHog from 'posthog-react-native'
export let posthog: PostHog | undefined = undefined
export const posthogAsync: Promise<PostHog> = PostHog.initAsync('<ph_project_api_key>', {
// PostHog API host (https://app.posthog.com by default)
host: '<ph_instance_address>'
})
posthogAsync.then(client => {
posthog = client
})
// app.ts
import { posthog, posthogAsync} from './posthog'
export function MyApp1() {
useEffect(async () => {
// Use posthog optionally with the possibility that it may still be loading
posthog?.capture('MyApp1 loaded')
// OR use posthog via the promise
(await posthogAsync).capture('MyApp1 loaded')
}, [])
return <View>Your app code</View>
}
// You can even use this instance with the PostHogProvider
export function MyApp2() {
return <PostHogProvider client={posthogAsync}>{/* 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.

TypeScript
export const posthog = await PostHog.initAsync("<ph_project_api_key>", {
// PostHog API host
host?: 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 flushes
flushInterval?: number = 10000
// If set to false, tracking will be disabled until `optIn` is called
enable?: boolean = true,
// Whether to track that `getFeatureFlag` was called (used by Expriements)
sendFeatureFlagEvent?: boolean = true,
// Whether to load feature flags when initialised or not
preloadFeatureFlags?: boolean = true,
// How many times we will retry HTTP requests
fetchRetryCount?: number = 3,
// The delay between HTTP request retries
fetchRetryDelay?: number = 3000,
// For Session Analysis how long before we expire a session
sessionExpirationTimeSeconds?: number = 1800 // 30 mins
// Whether to post events to PostHog in JSON or compressed format
captureMode?: '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 or react-native-navigation)
  • $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.

JSX
<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.

JSX
<View ph-no-capture>Sensitive view here</View>

Tracking Screen views and touches with @react-navigation/native:

JSX
// 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>
)
}

Tracking Screen views and touches with react-native-navigation:

JSX
import PostHog, { PostHogProvider } from 'posthog-react-native'
import { Navigation } from 'react-native-navigation';
export const posthogAsync = PostHog.initAsync('<ph_project_api_key>');
// Simplify the wrapping of your Screens with a shared PostHogProvider
export const SharedPostHogProvider = (props: any) => {
return (
<PostHogProvider client={posthogAsync} autocapture={{
captureLifecycleEvents: false, // Lifecycle events are handled differently for react-native-navigation
captureTouches: true,
}}>
{props.children}
</PostHogProvider>
);
};
export const MyScreen = () => {
return (
// Every screen needs to be wrapped with this provider if you want to capture touches or use the hook `usePostHog()`
<SharedPostHogProvider>
<View>
...
</View>
</SharedPostHogProvider>
);
};
Navigation.registerComponent('Screen', () => MyScreen);
Navigation.events().registerAppLaunchedListener(async () => {
(await posthogAsync).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,
},
});
});

Additional configuration

You can tweak how autocapture works by passing custom options.

TSX
<PostHogProvider apiKey="<ph_project_api_key>" autocapture={{
captureTouches: true, // If you don't want to capture touch events set this to false
captureLifecycleEvents: true, // If you don't want to capture the Lifecycle Events (e.g. Application Opened) set this to false
captureScreens: true, // If you don't want to capture screen events set this to false
ignoreLabels: [], // Any labels here will be ignored from the stack in touch events
customLabelProp: "ph-label",
noCaptureProp: "ph-no-capture",
propsToCapture = ["testID"], // Limit which props are captured. By default, identifiers and text content are captured.
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 so
routeToName: (name, params) => {
if (params.id) return `${name}/${params.id}`
return name
},
routeToParams: (name, params) => {
if (name === "SensitiveScreen") return undefined
return 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 database
  • userProperties with a dictionary with key: value pairs
JavaScript
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 or movie updated, in order to easily identify what your events mean later on (we know this from experience).

Optionally you can submit:

  • properties, which is an object with any information you'd like to add

For example:

JavaScript
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

JavaScript
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

JavaScript
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:

JavaScript
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:

JavaScript
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:

JavaScript
posthog.flush()
// or using async/await
await 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.

JavaScript
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.

JavaScript
posthog.optIn() // opt in
posthog.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

JavaScript
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 loaded
return null
}
return showFlaggedFeature ? <Text>Testing feature 😄</Text> : <Text>Not Testing feature 😢</Text>
}

Alternatively you can call load the feature flags directly:

JavaScript
// Defaults to undefined if not loaded yet or if there was a problem loading
posthog.getFeatureFlag('my-flag')
// Multi variant feature flags are returned as a string
posthog.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

JavaScript
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:

JavaScript
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.

JavaScript
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

Group analytics allows you to associate the events for that person's session with a group (e.g. teams, organizations, etc.). Read the Group Analytics guide for more information.

Note: This is a paid feature and is not available on the open-source or free cloud plan. Learn more here.

  • Associate the events for this session with a group
JavaScript
posthog.group('company', '42dlsfj23f')
posthog.capture('upgraded plan') // this event is associated with company ID `42dlsfj23f`
  • Associate the events for this session with a group AND update the properties of that group
JavaScript
posthog.group('company', '42dlsfj23f', {
name: 'Awesome Inc.',
employees: 11,
})

The name is a special property which is used in the PostHog UI for the name of the Group. If you don't specify a name property, the group ID will be used instead.

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.

JavaScript
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.

JSX
// DEPRECATED V1 Setup
import PostHog from 'posthog-react-native'
await PostHog.setup('phc_ChmcdLbC770zgl23gp3Lax6SERzC2szOUxtp0Uy4nTf', {
host: 'https://app.posthog.com',
captureApplicationLifecycleEvents: false, // Replaced by `PostHogProvider`
captureDeepLinks: false, // No longer supported
recordScreenViews: false, // Replaced by `PostHogProvider` supporting @react-navigation/native
flushInterval: 30, // Stays the same
flushAt: 20, // Stays the same
android: {...}, // No longer needed
iOS: {...}, // No longer needed
})
PostHog.capture("foo")
// V2 Setup difference
import 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 class
posthog.capture("foo")

Questions?

Was this page useful?

Next article

Ruby

The posthog-ruby library provides tracking functionality on the server-side for applications built in Ruby. It uses an internal queue to make calls fast and non-blocking. It also batches requests and flushes asynchronously, making it perfect to use in any part of your web app or other server-side application that needs performance. Installation Add this to your Gemfile : In your app, set your API key before making any calls. If setting a custom host , make sure to include the protocol (e.g…

Read next article