How to Implement Feature Flags in a React JS App
Tags: react, javascript, featureflags, tutorial
Published: 2021-07-05 14:25:31

We discuss three ways to implement feature flags in your React apps, from the DIY approach to third party cloud based solutions through open source libraries.

Feature flags, or toggles, as described by Martin Fowler are a "powerful technique, allowing teams to modify system behavior without changing code." In other words, implementing feature flags as a set of patterns is a robust way to manage code complexity and deliver new features to users using CI/CD pipelines, reducing the time to value and decreasing the risk of deploying buggy, error-ridden code to production.

In summary, there are 4 different types of feature flags each with a different use case:

- **Release flags:** These are temporary feature toggles, providing software developers with the ability to ship untested code as latent code that might never be turned on.
- **Experiment flags:** These flags or toggles are utilized to perform A/B or multivariate testing. This is a highly dynamic flag and is only functional until statistically significant results are generated before the flag is removed.
- **Ops flags:** These flags are usually short-lived and can be introduced when rolling out a new feature that has unclear performance implications, providing the operations team with the ability to disable this feature very quickly after the deployment has completed.
- **Permissioning flags:** Permissioning flags are generally long-lived and are used to manage the features and groups of features that specific groups of users can access, such as premium features that paying customers can access.

## Implementing feature flags inside React projects

[Feature flags](https://www.flagship.io/feature-flags/) are an integral part of deploying software updates via CI/CD pipelines without disrupting existing functionality. There are several ways to implement feature flags in your React apps. Let's consider three of the most popular and common ways:

1. The do-it-yourself method where the developer writes the feature flag code from scratch.
2. The use of open-source libraries that are integrated into the React Single-Page Application (SPA).
3. Signing up with a cloud based solution.

## Do it yourself: A simple and free solution

This method requires you to write code, switching feature flags on and off directly in JavaScript. By expanding on this method, let's consider a simple use case, including code samples from a feature flag React app project, before looking at the primary pros and cons of this method.

### 1. Setting up the React project

If you already have your React project set up, you can skip to the next section, "Adding new feature flags" otherwise, here is a step-by-step guide to setting up a new project.

The reactjs.org website notes that the create-react-app is the easiest way to develop a new single-page application with React.

Therefore, use the following code to create a new boilerplate app:

```
npx create-react-app my-app
cd my-app
npm start
```

### 2. Adding new feature flags

Now that we have the project created and an empty app template, let's look at how to add a feature flag in React.

Feature flags can be stored in different places such as a database server, inside local storage, or in a cookie. In this scenario, we will store them inside local storage.

The first step is to create a Reactjs feature flag file with the following format used to create new features. This will act as your config file that you'll update every time you want to turn on/off a specific feature.

```javascript
[{
    name: 'banner',
    description: 'Banner shown on top of the page',
    active: false
}]
```

Each feature flag must have a unique name that we can later call or reference in React. A short description is also needed to describe the functionality it adds and an active flag to determine whether the toggle is on or off.

As seen from the code snippet for creating a banner flag, our flags are stored inside an array.

To store these flags in local storage, add the following function to your app.js file and call it at the top of your feature component file.

Note: This will create 3 new feature flags if there are no feature flags created in local storage (localStorage). You also need to use the JSON.stringify () method to convert the JavaScript objects into strings as localStorage can only handle strings.

```jsx
const initFeatures = () => {
    if (!localStorage.getItem('flags')) {
        localStorage.setItem('flags', JSON.stringify([
            {name: 'banner', description: 'Banner shown on top of the page', active: false},
            {name: 'reporting-yn', description: 'Switch on reporting modules for premium clients', active: false},
            {name: 'info-message', description: 'Enhance info message with icon and link', active: true}
        ]));
    }
};

const App = () => {
    initFeatures();
    ...
}
```

### 3. Adding the feature component

In order to reference these feature flags in React and show/hide features based on these feature flags, you need to create a new React component <Feature />. Define it in a file called feature.js and store it in your src folder.

This component accepts 2 props:

- the flag name to check against,
- the child content to be used (children prop).
- The first step is to get the feature from localStorage and see if it is set to active or not. If the feature is active, we can render the feature; otherwise, we return null.

```jsx
const Feature = ({name, children}) => {
    const features = JSON.parse(localStorage.getItem('flags'));
    const feature = features.find(feature => feature.name === name);

    if (feature && feature.active) {
        return children;
    }

    return null;
};

export default Feature;
```

This component will handle the toggling of feature flags on and off. Finally, you just import and render the component where you need.

```jsx
import Feature from './feature';

const App = () => {
  initFeatures();
  return (
    <div className='App'>
      <Feature name='banner'>
        <Banner />
      </Feature>
    </div>
  );
};
export default App;
```

### Pros

There are several advantages to using this method. The most obvious being the fact that when writing your own feature flag code, it is free, easily accessible, and highly available for small React feature toggle projects.

### Cons

However, what happens when your application grows in scale, and you need to create and manage several different feature flags, both long- and short-lived?

This is where this method's disadvantages come to the fore. Succinctly stated, this method is difficult to scale where lots of flags are utilized. And as you can see from the code samples highlighted above, advanced features require more development work which can be challenging and complicated to maintain.

## Feature flag open-source libraries for React

The second method is to use existing libraries that you can find on NPM or Github. A simple search for "feature flag" will lead you to multiple open-source libraries or packages. Here are a few examples of these packages:

- [React-Feature-Flags](https://www.npmjs.com/package/react-feature-flags)
- [Feature-Toggle-API](https://www.npmjs.com/package/feature-toggle-api)
- [React Unleash Flags](https://www.npmjs.com/package/react-unleash-flags)
- [Flagged](https://github.com/sergiodxa/flagged)

Flagged, for instance, provides nice features such as:

- Hooks API
- High Order Component API
- Render Props API
- TypeScript Support
- Zero Dependencies
- Nested Flags

### Pros

The advantages of using these open-source libraries are that they are freely available, easy to use, and quick to set up. As described above, all you need to do is consume the libraries into your application and then call the functions created in the library files, passing in variables as required and reading returned variables to understand the state of your feature flags.

### Cons

However, as with everything, there are also disadvantages to using open-source feature flag libraries. The most prominent includes the fact that maintenance and evolution are not guaranteed, and the library's functional scope might not suit your app's specific requirements. In both cases, a fair amount of refactoring and new code development will have to take place to maintain the existing code and add the features specific to your application.

## Feature flag management platforms

The third and last way to implement feature flags in a single-page application is using a dedicated feature flag management 3rd-party service that provides a React integration.

By way of expanding on this statement, let's look at a step-by-step guide on how to set up feature flags in Flagship.io with the React SDK. As an alternative, you can also directly call the Flagship Decision API (REST API), but for the sake of simplicity we'll use the dedicated SDK that provides additional capabilities out of the box (ex: bucketing). The platform also provides additional SDKs for JAVA, Python, PHP, .Net, Go, iOS, Android, Flutter...

As a cloud-based feature management service, using Flagship.io is a 2- step process. First, in your codebase, you wrap your features once with flags using methods and providers from the React SDK. Once this is done, you remotely configure your flags (values, segments…) from the Flagship.io dashboard.

### 1. Set up the React SDK in your SPA project and wrap features with flags

Let's use the same project that we created in the first method (Setting up the project) using our create-react-app boilerplate app.

Install the SDK using NPM or yarn.

```
npm install @flagship.io/react-sdk
```

Import the Flagship provider from the React SDK which makes Flagship features available to the rest of your app. You can wrap your app directly within the app.js file.

The envID and apiKey props are required. You access them from the Flagship UI under the "Settings" section. For more information on the different props available, please refer to the [API references](https://developers.flagship.io/docs/sdk/react/v2.1).

```jsx
import React from "react";
import { FlagshipProvider } from "@flagship.io/react-sdk";

const App = () => (
  <>
    <FlagshipProvider
      envId="YOUR_ENV_ID"
      apiKey="YOUR_API_KEY"
      visitorData={{
        id: "YOUR_VISITOR_ID",
        context: {
          // some context
        },
        isAuthenticated: false,
      }}
      enableConsoleLogs={true}
    >
      {/* [...] */}
    </FlagshipProvider>
  </>
);
```

Then, from the React component you want to get access to your flags, import and use one of our React Hook. useFlagship hook is the most useful one from our React SDK. It gets modifications assigned to the current user as well as further functionalities, such as sending hit tracking, checking the SDK status…

```jsx
import { useFlagship } from "@flagship.io/react-sdk";

export const MyReactComponent = () => {
const fsParams = {
  modifications: {
    requested: [
      {
        key: "btnColor", // btnColor is your flag identifier that should be declared in the Flagship UI
        defaultValue: "green",
        activate: false,
      },
    ],
  },
};

const {
  modifications: fsModifications,
  status: fsStatus,
  hit: fsHit,
} = useFlagship(fsParams);

return (
    <div
      style={{
        height: "200px",
        width: "200px",
        backgroundColor: modifications.backgroundColor,
      }}
    >
      {"I'm a square with color=" + modifications.backgroundColor}
    </div>
  );
}
```

### 2. Declare your flags in the Flagship UI and set up values

The first step is to [sign up with Flagship.io](https://www.flagship.io/sign-up/) and sign into your account.

You can refer to this short video that goes through all the process of a feature flag setup or read the detailed instructions below.

#### Creating your feature flag use case

To create a feature flag from the dashboard, apply the following steps:

Go to the Flagship dashboard.

- Click the + button.
- Choose an existing project or create a new one
- Click the "Add a use case" button.
- You are presented with a list of different templates or use cases (ex: progressive rollout, A/B test...)
- Choose the "Feature toggling" template.

#### Entering the basic information

First, you need to enter the basic information of your feature flag use case:

- The feature name: use the most representative name for your feature, because this is the one you'll need to remember in case you want to find it later.
- The feature description: explain exactly what your feature deployment is about and what its purpose for your business is.
- The primary/secondary metric to follow (optional) which will serve as a point of reference to analyze performance. For more information, refer to Configuring KPIs.

#### Defining flags

This is where you configure the flags and their values based on your different scenarios. Think of it as the config file mentioned in the first method, but that you manage remotely from the cloud. Important: flag names you specify here should match the ones used in your codebase ("btnColor" in your code example above).

#### Defining targeting

During this step, you can define which users will be assigned to your different flag values. This is a segmentation engine built into the platform that makes it easy to assign flags conditionally based on user traits (or attributes) that you have access to in your codebase. Refer to this article about feature flag targeting for more information. The 3 following options are available:

- All Users if you want all your users to progressively see your feature.
- Users by ID if you want only users with a specific ID to see your feature.
- Key if you only want users matching this key value to see your feature.

#### Enabling your feature

Once you have configured your feature, it is OFF by default to allow you to check that it is correctly configured. Back to the dashboard, you can activate your feature ON when you are ready!

And that's it. Now, provided changes to your codebase have been deployed, you can activate/deactivate feature flags, remotely change their values and have your React App react instantly to these changes.

### Last thoughts

This article describes three ways of implementing feature flags in a React SPA (single-page application):

- the do-it-yourself method,
- using open-source libraries,
- signing up with a dedicated feature management platform.

While there are pros and cons to each approach, the third-party vendor option is probably the most efficient method for large teams with evolving use cases that don't want to deal with the [challenges of an in-house system](https://www.flagship.io/feature-flag-journey/).