PostHog makes it easy to get data about traffic and usage of your React app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.
This guide will walk you through an example integration of PostHog using React and the posthog-js library.
Installation
For installation with Next.js we'd recommend following the Next.js integration guide instead.
- Install posthog-js using your package manager
- Add your environment variables to your .env.localfile and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project API key in the PostHog app under Project Settings > API Keys.
- Integrate PostHog at the root of your app (src/index.jsfor the defaultcreate-react-app).
Usage
PostHog Provider
The React context provider makes it easy to access the posthog-js library in your app.
The provider can either take an initialized client instance OR an API key and an optional options object.
With an initialized client instance:
or with an API key and optional options object:
Using posthog-js functions
By default, the posthog-js library automatically captures pageviews, element clicks, inputs, and more. Autocapture can be tuned in with the configuration options.
If you want to use the library to identify users, capture events, use feature flags, or use other features, you can access the initialized posthog-js library using the usePostHog hook.
Do not directly import posthog apart from installation as shown above. This will likely cause errors as the library might not be initialized yet. Initialization is handled automatically when you use the PostHogProvider and hook.
All the methods of the library are available and can be used as described in the posthog-js documentation.
Feature flags
Feature flags are a powerful way to test new features and roll them out to a subset of your users. You can use feature flags to enable/disable features, change the behavior of a feature, or even change the UI of a feature.
PostHog provides several hooks to make it easy to use feature flags in your React app.
| Hook | Description | 
|---|---|
| useFeatureFlagEnabled | Returns a boolean indicating whether the feature flag is enabled. | 
| useFeatureFlagPayload | Returns the payload of the feature flag. | 
| useFeatureFlagVariantKey | Returns the variant key of the feature flag. | 
| useActiveFeatureFlags | Returns an array of active feature flags. | 
For example, to show a welcome message if the feature flag is enabled:
To show a different message depending on the variant key:
To load the message and title from the feature flag payload: