React Native product analytics 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

Terminal
npx expo install posthog-react-native expo-file-system expo-application expo-device expo-localization

React Native apps

Terminal
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_api_key>" 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:

React Native
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_api_key>', {
// 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:

React Native
import { posthog } from './posthog'
export function MyApp1() {
useEffect(async () => {
posthog.capture('event_name')
}, [posthog])
return <View>Your app code</View>
}

You can even use this instance with the PostHogProvider:

React Native
import { posthog } from './posthog'
export function MyApp() {
return <PostHogProvider client={posthog}>{/* Your app code */}</PostHogProvider>
}

Community questions

Was this page useful?

Questions about this page? or post a community question.