React Native web analytics installation

  1. Install the package

    Required

    Install the PostHog React Native library and its dependencies:

    npx expo install posthog-react-native expo-file-system expo-application expo-device expo-localization
  2. Configure PostHog

    Required

    PostHog is most easily used via the PostHogProvider component. Wrap your app with the provider:

    App.tsx
    import { PostHogProvider } from 'posthog-react-native'
    export function MyApp() {
    return (
    <PostHogProvider
    apiKey="<ph_project_api_key>"
    options={{
    host: "https://us.i.posthog.com",
    }}
    >
    <RestOfApp />
    </PostHogProvider>
    )
    }
  3. Track screen views

    Recommended

    Despite the name, the web analytics dashboard can be used to track screen views in mobile apps, too. Open your app and view some screens to generate some events.

    To automatically capture screen views with React Navigation, use the usePostHogCapture hook:

    App.tsx
    import { usePostHogCapture } from 'posthog-react-native'
    import { NavigationContainer } from '@react-navigation/native'
    function App() {
    const routeNameRef = useRef<string>()
    const navigationRef = useRef<NavigationContainerRef<any>>()
    const captureEvent = usePostHogCapture()
    return (
    <NavigationContainer
    ref={navigationRef}
    onReady={() => {
    routeNameRef.current = navigationRef.current?.getCurrentRoute()?.name
    }}
    onStateChange={async () => {
    const previousRouteName = routeNameRef.current
    const currentRouteName = navigationRef.current?.getCurrentRoute()?.name
    if (previousRouteName !== currentRouteName) {
    captureEvent('$screen', { $screen_name: currentRouteName })
    }
    routeNameRef.current = currentRouteName
    }}
    >
    {/* App content */}
    </NavigationContainer>
    )
    }
  4. Next steps

    Recommended

    After installing PostHog and ensuring autocapture is enabled, head to your web analytics dashboard to see your data. And then check out our getting started guide.

    PostHog tip: Web analytics works with anonymous events. This means if you are primarily using PostHog for web analytics, it can be significantly cheaper for you.

Community questions

Was this page useful?

Questions about this page? or post a community question.