DEV Community

Martijn de Haan
Martijn de Haan

Posted on • Edited on

Real-Time Feature Flags Using React Hooks

Are you building a feature which is not ready for prime time yet? But still want to show it to a select group of users? Do you want to skip the terrible thing which is called a staging environment? Look no more!

You are not alone. More and more teams are moving away from their staging environment to just simply use feature flags to control for which users a feature is enabled. Staging only adds latency to your feature delivery.

const MyComponent = () => {
  const { isEnabled } = useBoolean(`my-feature`);

  if (isEnabled) {
    return (
      <div>
        // New component here
      </div>
    );
  }

  return (
    <div>
      // Old component stuff here
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

This article is specifically about React, but we have different client libraries available. Check out the list at Boolean.

Getting started using feature flags is this easy. npm i @ff00ff/boolean-react and add the provider component in the root of your component tree and you're all set. You can sign up and create a free account at Boolean.

<BooleanProvider apiKey={process.env.BOOLEAN_API_KEY}>
  {/* Your component tree here */}
</BooleanProvider>
Enter fullscreen mode Exit fullscreen mode

When the BooleanProvider mounts, the library starts a WebSocket connection to get the initial state of your features. And when you toggle your features in the Boolean dashboard, the changes are pushed over these WebSocket connections to all your users. Instantly.

Advanced Targeting

There is more! Using Boolean, per feature, you can target specific users. This all happens without Boolean receiving a copy of the data you have on your users, because the rules are evaluated in the library. We think this privacy-first approach is really important.

// Prop drilling is just an example here, you can also use a hook or any other way to get the user data in
const MyComponent = ({ user }) => {
  const { isEnabled } = useBoolean(`my-feature`, user.id, {
    // Add whatever attributes you want here
    plan: user.plan,
  });

  if (isEnabled) {
    return (
      <div>
        // New component here
      </div>
    );
  }

  return (
    <div>
      // Old component stuff here
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now, in the Boolean dashboard, you can use the user's plan attribute to enable a feature based on the plan they have. You can read more on the library on the Boolean's React page.

I'm Martijn, founder of Boolean. If you have any questions just send me a ping. Are you ready to start using feature flags?

Top comments (0)