Unlocking Dynamic Features: GrowthBook’s Feature Flagging in React App
Tags: react, growthbook, javascript, tutorial
Published: 2023-10-02 17:00:19

### What is GrowthBook?

[Growthbook](https://docs.growthbook.io/) is an open source library specially used for feature flagging and A/B Testing.

Here we are going to discuss how we can integrate it with React JS Application. 

GrowthBook provides cloud hosted environment for quick start and we are going to use it in this example.

#### STEP 1 :

Let's create a feature flag in the GrowthBook App. Go to GrowthBook https://app.growthbook.io and just register yourself in the website. 

Create a SDK Connection and generate your client key to integrate it in the App.

![SDK Connection](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6fycym6faqnrd9a0t9z8.png)

#### STEP 2 :

Let's integrate in the App:

###### Installation:

For npm :
```javascript
npm install @growthbook/growthbook-react
```

For yarn:

```javascript
yarn add @growthbook/growthbook-react
```

After successful installation, let's write some code:

In your `App.js` File , create a new GrowthBook instance with your host and generated API key. We have to wrap our app around `GrowthBookProvider`. 
To load all the features created in your GrowthBook app, we can add `loadFeatures` method from growthBook object. 
This will handle network request with the given host and key and initialize the SDK.

```javascript
import { useEffect } from "react";
import { Header } from "./Header";
import "./styles.css";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";

const gb = new GrowthBook({
  apiHost: "https://cdn.growthbook.io",
  clientKey: "key-123"
});

export default function App() {
  useEffect(() => {
    gb.loadFeatures();
  }, []);

  return (
    <GrowthBookProvider growthbook={gb}>
      <div className="App">
        <Header />
      </div>
    </GrowthBookProvider>
  );
}
```
Make sure you will replace your `clientKey` here.

#### STEP 3 :

We can create the flag in features tab in GrowthBook App as shown in the snapshot.

![Feature Flag Creation](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4ml29l6yx0ar9mmecm4h.png)

Let's start using feature flagging:

Go to your `Header.js` file :

```javascript
import { useFeatureIsOn } from "@growthbook/growthbook-react";

export function Header() {

  // Boolean on/off features
  const enabled = useFeatureIsOn("show-header");

  if (enabled) {
    return <div>This is the Header</div>;
  } else {
    return <div>This is a different Header</div>;
  }
}
```

You can see the visible Header:

![Working App](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wlpkotjz2tmjgjequ02.png)

And you are good to go!! Link to this [project]
(https://codesandbox.io/s/growthbook-integration-g623zm)

### Integration using Fetch API:

If you pass an apiHost and clientKey into the GrowthBook constructor, it will handle the network requests, caching, retry logic, etc. for you automatically but if you want to handle them on your own you can do it by simply writing a fetch API call. 
This can be used if you are hosting on your own and need to pass additional headers including token through the App.

Let's see the implementation here:

```javascript
import { useEffect } from "react";
import { Header } from "./Header";
import "./styles.css";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";

const gb = new GrowthBook({
  attributes: {
    country: "Spain"
  }
});

const API_ENDPOINT =
  process.env.REACT_APP_GROWTH_BOOK_API_HOST +
  "api/features/" +
  process.env.REACT_APP_GROWTH_BOOK_KEY;

const getFeatures = () => {
  fetch(API_ENDPOINT)
    .then((response) => response.json())
    .then((data) => {
      gb.setFeatures(data.features);
    })
    .catch((err) => console.error(err));
};

export default function App() {
  useEffect(() => {
    getFeatures();
  }, []);

  return (
    <GrowthBookProvider growthbook={gb}>
      <div className="App">
        <Header />
      </div>
    </GrowthBookProvider>
  );
}
```

This will handle your network request in the same way, make sure that you append `api/features/` to the host URL. 
It's always a good practice to keep all the url and keys in the .env file. [Sample Project Link](https://codesandbox.io/s/growthbook-fetch-y6wy4k)

### Setup Rules over Feature Flags:

We can also add condition to our flags. In the growthbook app, go to **Override Rules** and add force rule according to your condition. Here I have added a condition that specifies the header should only be displayed if the country is Spain. 

![Attributes](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/njlpa3czkr2ant0smchp.png)

Attributes can be configured at the default level.

```javascript
const gb = new GrowthBook({
  attributes: {
    country: "Spain"
  }
});
```
If attributes change, you can call `setAttributes()` to update. This will completely overwrite any existing attributes.

```javascript
 useEffect(() => {
    gb.setAttributes({
      country: user.country
    });
  }, [user.country])
```

#### Final Words:

We have explored how the basic implementation of Growthbook works in integration with React. Now we can go ahead and implement it.

1. Read more about it here [DOCS](https://docs.growthbook.io/lib/react)
2. Also, try to work around [A/B Testing](https://docs.growthbook.io/assets/files/open-guide-to-ab-testing.v1.0-228e9312b957a9716766cd8887b18a11.pdf)
3. Sample Project link using default load features method [Project Link]
(https://codesandbox.io/s/growthbook-integration-g623zm)
4. Sample project using fetch API call [Project Link](https://codesandbox.io/s/growthbook-fetch-y6wy4k)