# @posthog/react React components and hooks for PostHog analytics integration. [SEE FULL DOCS](https://posthog.com/docs/libraries/react) ## Installation ```bash npm install @posthog/react posthog-js ``` ## Usage ### Setting up the Provider 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('', { api_host: 'https://us.i.posthog.com' }) function App() { return ( ) } ``` ### Hooks #### 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
Config: {JSON.stringify(payload)}
} ``` #### 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}
  • ))}
) } ``` ### Components #### 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](https://www.posthog.com/docs). ## Questions? ### [Check out our community page.](https://posthog.com/posts)