React feature flags installation
- 1
Install the package
RequiredInstall
posthog-jsand@posthog/reactusing your package manager: - 2
Add environment variables
RequiredAdd your PostHog API key and host to your environment variables. For Vite-based React apps, use the
VITE_PUBLIC_prefix:.env - 3
Initialize PostHog
RequiredWrap your app with the
PostHogProvidercomponent at the root of your application (such asmain.tsxif you're using Vite):main.tsxdefaults optionThe
defaultsoption automatically configures PostHog with recommended settings for new projects. See SDK defaults for details. - 4
Accessing PostHog in your code
RecommendedUse the
usePostHoghook to access the PostHog instance in any component wrapped byPostHogProvider:MyComponent.tsxYou can also import
posthogdirectly for non-React code or utility functions:utils/analytics.ts - 5
Send events
RecommendedClick around and view a couple pages to generate some events. PostHog automatically captures pageviews, clicks, and other interactions for you.
If you'd like, you can also manually capture custom events:
JavaScript - 6
Use feature flags
RequiredPostHog provides several hooks to make it easy to use feature flags in your React app. Use
useFeatureFlagEnabledfor boolean flags:Multivariate flags
For multivariate flags, use
useFeatureFlagVariantKey:Flag payloads
The
useFeatureFlagPayloadhook does not send a$feature_flag_calledevent, which is required for experiments. Always use it withuseFeatureFlagEnabledoruseFeatureFlagVariantKey:The
PostHogFeaturecomponent simplifies code by handling feature flag related logic:App.tsxThe
matchprop 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 thefallbackprop.If your flag has a payload, you can pass a function to children whose first argument is the payload:
App.tsx - 7
Running experiments
OptionalExperiments run on top of our feature flags. Once you've implemented the flag in your code, you run an experiment by creating a new experiment in the PostHog dashboard.
- 8
Next steps
RecommendedNow that you're evaluating flags, continue with the resources below to learn what else Feature Flags enables within the PostHog platform.
Resource Description Creating a feature flag How to create a feature flag in PostHog Adding feature flag code How to check flags in your code for all platforms Framework-specific guides Setup guides for React Native, Next.js, Flutter, and other frameworks How to do a phased rollout Gradually roll out features to minimize risk More tutorials Other real-world examples and use cases