React
Contents
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 walks you through an example integration of PostHog using React and the posthog-js library.
Beta: integration via LLM
Install PostHog for React in seconds with our wizard by running this prompt with LLM coding agents like Cursor and Bolt, or by running it in your terminal.
Or, to integrate manually, continue with the rest of this guide.
Installation
For Next.js, we recommend following the Next.js integration guide instead.
- Install
posthog-js
using your package manager:
- Add your environment variables to your
.env.local
file 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.jsx
if you are using Vite).
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 usePostHog
hook.
Using React Router v7?
You need to set posthog-js
and posthog-js/react
as external packages in your vite.config.ts
file to avoid SSR errors.
See our Remix docs for more details.
Set up a reverse proxy (recommended)
We recommend setting up a reverse proxy, so that events are less likely to be intercepted by tracking blockers.
We have our own managed reverse proxy service included in the platform packages, which routes through our infrastructure and makes setting up your proxy easy.
If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using Cloudflare, AWS Cloudfront, and Vercel.
Grouping products in one project (recommended)
If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and group them in one project.
This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms.
Usage
PostHog provider
The React context provider makes it easy to access the posthog-js
library in your app.
The provider takes an initialized and configured client instance like this:
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. This sends a $feature_flag_called event. |
useFeatureFlagVariantKey | Returns the variant key of the feature flag. This sends a $feature_flag_called event. |
useActiveFeatureFlags | Returns an array of active feature flags. This does not send a $feature_flag_called event. |
useFeatureFlagPayload | Returns the payload of the feature flag. This does not send a $feature_flag_called event. Always use this with useFeatureFlagEnabled or useFeatureFlagVariantKey . |
Example 1: Using a boolean feature flag
Example 2: Using a multivariate feature flag
Example 3: Using a flag payload
The useFeatureFlagPayload
hook does not send a $feature_flag_called
event, which is required for the experiment to be tracked. To ensure the exposure event is sent, you should always use the useFeatureFlagPayload
hook with either the useFeatureFlagEnabled
or useFeatureFlagVariantKey
hook.
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
PostHogProvider
at the top level for this to work.
Here is an example:
The
match
on the component can be eithertrue
, 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
fallback
attribute.
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.