Unlocking Dynamic Features: GrowthBook’s Feature Flagging in React App

Saloni Agrawal - Oct 2 '23 - - Dev Community

What is GrowthBook?

Growthbook 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

STEP 2 :

Let's integrate in the App:

Installation:

For npm :

npm install @growthbook/growthbook-react
Enter fullscreen mode Exit fullscreen mode

For yarn:

yarn add @growthbook/growthbook-react
Enter fullscreen mode Exit fullscreen mode

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.

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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

Let's start using feature flagging:

Go to your Header.js file :

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>;
  }
}
Enter fullscreen mode Exit fullscreen mode

You can see the visible Header:

Working App

And you are good to go!! Link to this project

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:

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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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

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

Attributes can be configured at the default level.

const gb = new GrowthBook({
  attributes: {
    country: "Spain"
  }
});
Enter fullscreen mode Exit fullscreen mode

If attributes change, you can call setAttributes() to update. This will completely overwrite any existing attributes.

 useEffect(() => {
    gb.setAttributes({
      country: user.country
    });
  }, [user.country])
Enter fullscreen mode Exit fullscreen mode

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
  2. Also, try to work around A/B Testing
  3. Sample Project link using default load features method Project Link
  4. Sample project using fetch API call Project Link
. . .