Skip to main content
The PostHog React integration provides a seamless way to add analytics, feature flags, and session replay to your React applications using hooks and context providers.

Installation

Install both posthog-js and the React wrapper:

Setup

1

Add environment variables

Create or update your .env file with your PostHog credentials. For Vite-based apps, use the VITE_PUBLIC_ prefix:
.env
For Create React App, use the REACT_APP_ prefix:
.env
2

Wrap your app with PostHogProvider

Add the PostHogProvider at the root of your application (typically in main.tsx or index.tsx):
The defaults option automatically configures PostHog with recommended settings. See SDK defaults for details.
3

Verify installation

Check your browser’s developer console for PostHog logs, or visit your Activity feed to see events.

Using the usePostHog Hook

Access the PostHog instance in any component using the usePostHog hook:
MyComponent.tsx

Capturing Events

Custom Events

Track Component Lifecycle

Identifying Users

On Login

On Logout

Feature Flags

useFeatureFlagEnabled Hook

Check if a feature flag is enabled:

useFeatureFlagVariantKey Hook

Get the variant of a multivariate flag:

useFeatureFlagPayload Hook

Retrieve feature flag payload data:

Manual Flag Checking

Accessing PostHog Outside Components

For utility functions or non-React code:
utils/analytics.ts

React Router Integration

Track route changes automatically:
App.tsx

Group Analytics

Track events for organizations or teams:

Advanced Configuration

Privacy Controls

Mask sensitive elements in session replay:

TypeScript Support

The SDK includes full TypeScript support:

Debugging

Enable debug mode during development:

Best Practices

Provider Placement: Always place PostHogProvider as high as possible in your component tree to ensure all components have access.
Avoid Over-tracking: Don’t track every click. Focus on meaningful user actions that help you understand product usage.
Use Hooks: Prefer usePostHog and feature flag hooks over importing posthog-js directly for better React integration.
Reset on Logout: Always call posthog.reset() when users log out to prevent data leakage between accounts.

Next Steps

Next.js Integration

Add PostHog to Next.js with SSR support

Feature Flags

Learn advanced feature flag patterns

Session Replay

Configure privacy and recording options

JavaScript SDK

Full JavaScript SDK reference