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 Next.js, we recommend following the Next.js integration guide instead.
- Install posthog-jsusing 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 and host in your project settings. IncludingVITE_PUBLIC_in their names ensures they are accessible in the frontend.
- Integrate PostHog at the root of your app (such as main.jsxif you are using Vite).
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.
TypeError: Cannot read properties of undefined
If you see the error TypeError: Cannot read properties of undefined (reading '...') this is likely because you tried to call a posthog function when posthog was not initialized (such as during the initial render). On purpose, we still render the children even if PostHog is not initialized so that your app still loads even if PostHog can't load.
To fix this error, add a check that posthog has been initialized such as:
Typescript helps protect against these errors.
Feature Flags
PostHog's feature flags enable you to safely deploy and roll back new features as well as target specific users and groups with them.
There are two ways to implement feature flags in React:
- Using hooks.
- Using the <PostHogFeature>component.
Method 1: Using hooks
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. | 
Example 1: Using a boolean feature flag
Example 2: Using a multivariate feature flag
Example 3: Using a flag payload
Method 2: Using the PostHogFeature component
The PostHogFeature component simplifies code by handling feature flag related logic. 
It also automatically captures metrics, like how many times a user interacts with this feature.
Note: You still need the
PostHogProviderat the top level for this to work.
Here is an example:
- The - matchon the component can be either- true, or the variant key, to match on a specific variant.
- If you also want to show a default message, you can pass these in the - fallbackattribute.
If you wish to customise logic around when the component is considered visible, you can pass in visibilityObserverOptions to the feature. These take the same options as the IntersectionObserver API. By default, we use a threshold of 0.1. 
Payloads
If your flag has a payload, you can pass a function to children whose first argument is the payload. For example:
Request timeout
You can configure the feature_flag_request_timeout_ms parameter when initializing your PostHog client to set a flag request timeout. This helps prevent your code from being blocked in the case when PostHog's servers are too slow to respond. By default, this is set at 3 seconds.
Error handling
When using the PostHog SDK, it's important to handle potential errors that may occur during feature flag operations. Here's an example of how to wrap PostHog SDK methods in an error handler:
Bootstrapping Flags
Since there is a delay between initializing PostHog and fetching feature flags, feature flags are not always available immediately. This makes them unusable if you want to do something like redirecting a user to a different page based on a feature flag.
To have your feature flags available immediately, you can initialize PostHog with precomputed values until it has had a chance to fetch them. This is called bootstrapping. After the SDK fetches feature flags from PostHog, it will use those flag values instead of bootstrapped ones.
For details on how to implement bootstrapping, see our bootstrapping guide.
Experiments (A/B tests)
Since experiments use feature flags, the code for running an experiment is very similar to the feature flags code:
It's also possible to run experiments without using feature flags.