React experiments 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
Implement your experiment
RequiredExperiments run on top of our feature flags. You can define which version of your code runs based on the return value of the feature flag.
You can use the
useFeatureFlagVariantKeyhook or thePostHogFeaturecomponent: - 6
Run your experiment
RequiredOnce you've implemented the feature flag in your code, you'll enable it for a target audience by creating a new experiment in the PostHog dashboard.
- 7
Next steps
RecommendedNow that you're running experiments, continue with the resources below to learn what else Experiments enables within the PostHog platform.
Resource Description Creating an experiment How to create an experiment in PostHog Adding experiment code How to implement experiments for all platforms Statistical significance Understanding when results are meaningful Experiment insights How to analyze your experiment data More tutorials Other real-world examples and use cases