GrowthBook React Client Library

This is a thin wrapper on top of the Javascript Library, so you might want to view those docs first to familiarize yourself with the basic classes and methods.

Installation

yarn add @growthbook/growthbook-react

or

npm install --save @growthbook/growthbook-react

Quick Usage

Step 1: Configure your app

import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";

// Create a GrowthBook instance
const growthbook = new GrowthBook();

// Load feature definitions (from API, database, etc.)
await fetch("https://s3.amazonaws.com/myBucket/features.json")
  .then((res) => res.json())
  .then((parsed) => {
    growthbook.setFeatures(parsed);
  });

export default function App() {
  return (
    <GrowthBookProvider growthbook={growthbook}>
      <OtherComponent />
    </GrowthBookProvider>
  );
}

Step 2: Start feature flagging!

There are a few ways to use feature flags in GrowthBook:

useFeature hook

import { useFeature } from "@growthbook/growthbook-react";

export default function OtherComponent() {
  // Boolean on/off flags
  const newLogin = useFeature("new-login-form").on;

  // Multivariate or string/JSON values
  const buttonColor = useFeature("login-button-color").value || "blue";

  if (newLogin) {
    return <NewLogin color={buttonColor} />;
  } else {
    return <Login color={buttonColor} />;
  }
}

IfFeatureEnabled component

import { IfFeatureEnabled } from "@growthbook/growthbook-react";

export default function OtherComponent() {
  return (
    <div>
      <h1>Hello!</h1>
      <IfFeatureEnabled feature="welcome-message">
        <p>Welcome to our site!</p>
      </IfFeatureEnabled>
    </div>
  );
}

FeatureString component

import { FeatureString } from "@growthbook/growthbook-react";

export default function OtherComponent() {
  return (
    <div>
      <h1>
        <FeatureString feature="site-h1" default="My Site" />
      </h1>
    </div>
  );
}

useGrowthBook hook

If you need low-level access to the GrowthBook instance for any reason, you can use the useGrowthBook hook:

import { useGrowthBook } from "@growthbook/growthbook-react";

export default function OtherComponent() {
  // Identical to: const feature = useFeature("my-feature")
  const growthbook = useGrowthBook();
  const feature = growthbook.feature("my-feature");
}

Step 3: Use Targeting Attributes

You can specify attributes about the current user and request. These are used for two things:

  1. Feature targeting (e.g. paid users get one value, free users get another)
  2. Assigning persistent variations in A/B tests (e.g. user id "123" always gets variation B)

The following are some comonly used attributes, but use whatever makes sense for your application.

new GrowthBook({
  attributes: {
    id: "123",
    environment: "prod",
    loggedIn: true,
    deviceId: "abc123def456",
    company: "acme",
    paid: false,
    url: "/pricing",
    browser: "chrome",
    mobile: false,
    country: "US",
  },
});

If you need to set or update attributes asynchronously, you can do so with setAttributes(). This will completely overwrite the attributes object with whatever you pass in. Also, be aware that changing attributes may change the assigned feature values. This can be disorienting to users if not handled carefully.

Step 4: Set up a Tracking Callback

Any time an experiment is run to determine the value of a feature, we call a function so you can record the assigned value in your event tracking or analytics system of choice.

new GrowthBook({
  trackingCallback: (experiment, result) => {
    // Example using Segment.io
    analytics.track("Experiment Viewed", {
      experimentId: experiment.key,
      variationId: result.variationId,
    });
  },
});

Inline Experiments

Depending on how you configure feature flags, they may run A/B tests behind the scenes to determine which value gets assigned to the user.

Sometimes though, you want to run an inline experiment without going through a feature flag first. For this, you can use either the useExperiment hook or the Higher Order Component withRunExperiment:

useExperiment hook

import { useExperiment } from "@growthbook/growthbook-react";

export default function OtherComponent() {
  const { value } = useExperiment({
    key: "new-headline",
    variations: ["Hello", "Hi", "Good Day"],
  });

  return <h1>{value}</h1>;
}

Class Components

Note: This library uses hooks internally, so still requires React 16.8 or above.

import { withRunExperiment } from "@growthbook/growthbook-react";

class OtherComponent extends React.Component {
  render() {
    // The `runExperiment` prop is identical to the `useExperiment` hook
    const { value } = this.props.runExperiment({
      key: "headline-test",
      variations: ["Hello World", "Hola Mundo"],
    });
    return <h1>{value}</h1>;
  }
}
// Wrap your component in `withRunExperiment`
export default withRunExperiment(OtherComponent);