Provides components and hooks for React integrations of PostHog.
npm install @posthog/reactReact components and hooks for PostHog analytics integration.
``bash`
npm install @posthog/react posthog-js
Wrap your application with PostHogProvider to make the PostHog client available throughout your app:
`tsx
import { PostHogProvider } from '@posthog/react'
function App() {
return (
)
}
`
Or pass an existing PostHog client instance:
`tsx
import posthog from 'posthog-js'
import { PostHogProvider } from '@posthog/react'
// Initialize your client
posthog.init('
function App() {
return (
)
}
`
#### usePostHog
Access the PostHog client instance to capture events, identify users, etc.
`tsx
import { usePostHog } from '@posthog/react'
function MyComponent() {
const posthog = usePostHog()
const handleClick = () => {
posthog.capture('button_clicked', { button_name: 'signup' })
}
return
}
`
#### useFeatureFlagEnabled
Check if a feature flag is enabled for the current user.
`tsx
import { useFeatureFlagEnabled } from '@posthog/react'
function MyComponent() {
const isEnabled = useFeatureFlagEnabled('new-feature')
if (isEnabled) {
return
}
return
}
`
#### useFeatureFlagVariantKey
Get the variant key for a multivariate feature flag.
`tsx
import { useFeatureFlagVariantKey } from '@posthog/react'
function MyComponent() {
const variant = useFeatureFlagVariantKey('experiment-flag')
if (variant === 'control') {
return
}
if (variant === 'test') {
return
}
return null
}
`
#### useFeatureFlagPayload
Get the payload associated with a feature flag.
`tsx
import { useFeatureFlagPayload } from '@posthog/react'
function MyComponent() {
const payload = useFeatureFlagPayload('feature-with-payload')
return
#### useActiveFeatureFlags
Get all active feature flags for the current user.
`tsx
import { useActiveFeatureFlags } from '@posthog/react'function MyComponent() {
const activeFlags = useActiveFeatureFlags()
return (
{activeFlags?.map((flag) => (
- {flag}
))}
)
}
`$3
#### PostHogFeature
A component that renders content based on a feature flag's value. Automatically tracks feature views and interactions.
`tsx
import { PostHogFeature } from '@posthog/react'function MyComponent() {
return (
}>
)
}
// With variant matching
function MyComponent() {
return (
}>
)
}
// With payload as render function
function MyComponent() {
return (
{(payload) => }
)
}
`#### PostHogErrorBoundary
An error boundary that captures React errors and reports them to PostHog.
`tsx
import { PostHogErrorBoundary } from '@posthog/react'function App() {
return (
)
}
``Please see the main PostHog docs.