How to set up React feature flags
Sep 14, 2023
Feature flags help you release features and conditional show content in your React apps. This tutorial shows you how to create a basic React app, add PostHog, create a feature flag, and then implement the flag to control content in your app.
Create your React app
First, we create our React app using create-react-app and go into the newly created react-flags folder.
We then remove the boilerplate code in src/App.js to simplify it to just a title.
Finally, run npm start and go to http://localhost:3000/ to see our new homepage.

Adding PostHog
Since PostHog handles the management and evaluation of feature flags, we must set it up in our app. To do this, start by installing the posthog-js library to get access to the React SDK.
Once, installed we can import PostHog into src/index.js and set up a client using our project API key and instance address from our project settings. We can wrap our app in the React PostHogProvider to access PostHog in any component.
Once done, go back to your app running locally, refresh, and you should see an event autocaptured into your PostHog instance.

Creating a feature flag
With PostHog set up, your React app is ready for feature flags. To create one, go to the feature flags tab in PostHog and click "New feature flag." Enter a flag key (like cool-react-homepage), set the release condition to roll out to 100% of users, and press "Save."

You can customize your conditions with percentage and person or group properties to fit your needs.
Adding our feature flag
Once created, we can add our feature flag to our React app. We do this using the useFeatureFlagEnabled hook to conditionally show new content in our component.
With the flag enabled, our app now shows "Welcome to my cool new React app."

Want to remove the flicker while loading? Read our tutorial on How to bootstrap feature flags in React and Express.
Using the PostHog feature component
An alternate way to implement feature flags is to use the PostHogFeature component. This simplifies the logic of using flags as well as captures related usage automatically (such as a $feature_view event). We set the old content as the fallback for the component.
These are basic implementations of React feature flags setup. From here, you can set up A/B tests, a public beta program, or canary releases.
Further reading
- Testing frontend feature flags with React, Jest, and PostHog
- How to add popups to your React app with feature flags
- How to set up analytics in React
Subscribe to our newsletter
Product for Engineers
Sharing what we learn about building successful products. Read by 25,000+ founders and developers.
We'll share your email with Substack