@featbit/react-client-sdk

中文文档
4.4.2发布于 2026/11/04Apache-2.0TypeScriptES Module近 30 天下载 4.7万

FeatBit client SDK for React

原始使用文档
文档目录14 节
  1. Introduction
  2. Getting started
  3. Install
  4. Prerequisite
  5. Quick Start
  6. Examples
  7. SDK
  8. Initializing the SDK
  9. Configuring the React SDK
  10. Consuming flags
  11. Switch user after initialization
  12. Populating the SDK with fallback flag values
  13. Flag keys
  14. Importing types

FeatBit Client-Side SDK for ReactJS

Introduction

This is the React client side SDK for the feature management platform FeatBit.

Be aware, this is a client side SDK, it is intended for use in a single-user context, which can be mobile, desktop or embeded applications. This SDK can only be ran in a browser environment, it is not suitable for React Native projects. If you are looking for React Native SDK, please check this React Native SDK.

The React SDK is based on the JavaScript SDK
The React SDK builds on FeatBit's JavaScript SDK to provide a better integration for use in React applications. As a result, much of the JavaScript SDK functionality is also available for the React SDK to use.

SDK version compatibility
The React SDK is compatible with React version 16.3.0 and higher. The React SDK offers two custom hooks. If you want to use these, then you must use React version 16.8.0 or higher. To learn more, read the section Using Hooks.

Using with Next.js If you are using this SDK with Next.js project, be aware that the SDK is not compatible with server-side rendering. You should use the SDK in the client side only. If you want to use the SDK in the server side, you should use @featbit/node-server-sdk.

Getting started

Install

npm install @featbit/react-client-sdk

Prerequisite

Before using the SDK, you need to obtain the environment secret and SDK URLs.

Follow the documentation below to retrieve these values

Quick Start

The following code demonstrates:

  1. Initialize the SDK
  2. Evaluate flag with userFlags hook
import { createRoot } from 'react-dom/client';
import { asyncWithFbProvider, useFlags, FbProvider } from '@featbit/react-client-sdk';

function Game() {
  return (
    <div>
      This is a game
    </div>
  );
}

function APP() {
  const flags = useFlags();

  const gameEnabled = flags['game-enabled'];

  return (
    <div>
      <div>{ gameEnabled ? <Game /> : <div>The game is not enabled</div>}</div>
    </div>
  );
}

(async () => {
  const configWithAnonymousUser = {
    options: {
      user: {
        name: 'the user name',
        keyId: 'fb-demo-user-key',
        customizedProperties: []
      },
      sdkKey: 'YOUR ENVIRONMENT SECRET',
      streamingUri: 'THE STREAMING URL',
      eventsUri: 'THE EVENTS URL'
    }
  };
  
  const root = createRoot(document.getElementById('root'));
  const Provider = await asyncWithFbProvider(configWithAnonymousUser);
  root.render(
    <Provider>
      <Game />,
    </Provider>
  );
  
  // Use the following code in React < 18.0.0
  // ReactDOM.render(
  //   <FbProvider>
  //     <APP/>
  //   </FbProvider>,
  //   document.getElementById('root')
  // );
})();

Examples

SDK

Initializing the SDK

After you install the dependency, initialize the React SDK. You can do this in one of two ways:

  • Using the asyncWithFbProvider function
  • Using the withFbProvider function

Both rely on React's Context API which lets you access your flags from any level of your component hierarchy.

Initializing using asyncWithFbProvider

The asyncWithFbProvider function initializes the React SDK and returns a provider which is a React component. It is an async function. It accepts a ProviderConfig object.

asyncWithFbProvider cannot be deferred. You must initialize asyncWithFbProvider at the app entry point prior to rendering to ensure flags and the client are ready at the beginning of the app.

import { createRoot } from 'react-dom/client';
import { asyncWithFbProvider } from '@featbit/react-client-sdk';

(async () => {
  const config = {
    options: {
      sdkKey: 'YOUR ENVIRONMENT SECRET',
      streamingUri: 'THE STREAMING URL',
      eventsUri: 'THE EVENTS URL',
      user: {
        name: 'USER NAME',
        keyId: 'USER ID',
        customizedProperties: [
          {
            "name": "age",
            "value": '18'
          }
        ]
      }
    }
  }

  const root = createRoot(document.getElementById('root'));
  const FbProvider = await asyncWithFbProvider(config);
  root.render(
    <FbProvider>
      <YourApp />,
    </FbProvider>
  );
})();

After initialization is complete, your flags and the client become available at the start of your React app lifecycle. This ensures your app does not flicker due to flag changes at startup time.

Rendering may be delayed
Because the asyncWithFbProvider function is asynchronous, the rendering of your React app is delayed until initialization is completed. This can take up to 100 milliseconds, but often completes sooner. Alternatively, you can use the withFbProvider function if you prefer to render your app first and then process flag updates after rendering is complete.

This function requires React 16.8.0 or later
The asyncWithFbProvider function uses the Hooks API, which requires React version 16.8.0 or later.

Initializing using withFbProvider

The withFbProvider function initializes the React SDK and wraps your root component in a Context.Provider. It accepts a ProviderConfig object used to configure the React SDK.

import { withFbProvider } from '@featbit/react-client-sdk';

const config = {
  options: {
    sdkKey: 'YOUR ENVIRONMENT SECRET',
    streamingUri: 'THE STREAMING URL',
    eventsUri: 'THE EVENTS URL',
    user: {
      name: 'USER NAME',
      keyId: 'USER ID',
      customizedProperties: [
        {
          "name": "age",
          "value": '18'
        }
      ]
    }
  }
};

export default withFbProvider(config)(YourApp);

Subscribing to flag changes

The React SDK automatically subscribes to flag change events. This is different from the JavaScript SDK, where customers need to opt in to event listening.

Configuring the React SDK

The ProviderConfig object provides configuration to both withFbProvider and asyncWithFbProvider function.

The only mandatory property is the options, it is the config needed to initialize the @featbit/js-client-sdk. To know more details about the options, please refer to @featbit/js-client-sdk. All other properties are React SDK related.

The complete liste of the available properties:

  • options: the initialization config for @featbit/js-client-sdk. mandatory

    You can use the options.bootstrap option to populate the SDK with default values.

  • reactOptions: You can use this option to enable automatic camel casing of flag keys when using the React SDK. the default value is false not mandatory

  • deferInitialization: This property allows SDK initialization to be deferred until you define the fbClient property. the default value is false not mandatory

    asyncWithFbProvider does not support deferInitialization. You must initialize asyncWithFbProvider at the app entry point prior to rendering to ensure flags and the client are ready at the beginning of your app.

    By deferring SDK initialization, you defer all steps which take place as part of SDK initialization, including reading flag values from local storage and sending the SDK's ready event.

    The one exception to this rule is that the SDK continues to load bootstrapped flag values as long as the bootstrapped values are provided as a map of flag keys and values. If you indicate that the SDK should bootstrap flags from local storage, this will not happen until the SDK initializes.

The following is an example ProviderConfig object including each of the above properties:

{
  options: {
    sdkKey: 'YOUR ENVIRONMENT SECRET',
    streamingUri: 'THE STREAMING URL',
    eventsUri: 'THE EVENTS URL',
    user: {
      name: 'USER NAME',
      keyId: 'USER ID',
      customizedProperties: [
        {
          "name": "age",
          "value": '18'
        }
      ]
    }
    ...
  },
  reactOptions: {
    useCamelCaseFlagKeys: false
  },
  deferInitialization: false
}

Consuming flags

Consuming flags in class component

There are two ways to consume the flags.

Using contextType property
import { context } from '@featbit/react-client-sdk';

class MyComponent extends React.Component {
  static contextType = context;

  constructor(props) {
    super(props);
  }

  render() {
    const { flags } = this.context;

    return (
      <div>{ flags['dev-test-flag'] ? 'Flag on' : 'Flag off' }</div>
    )
  }
}

export default MyComponent;
Using withFbConsumer

The return value of withFbConsumer is a wrapper function that takes your component and returns a React component injected with flags & fbClient as props.

import { withFbConsumer } from '@featbit/react-client-sdk';

class MyComponent extends React.Component {
  render() {
    const { flags } = this.props;

    return (
      <div>
        <div>{flags.flag1}</div>
      </div>
    );
  }
}

export default withFbConsumer()(Board)

Consuming flags in function component

There are two ways to consume the flags.

Using withFbConsumer

The return value of withFbConsumer is a wrapper function that takes your component and returns a React component injected with flags & fbClient as props.

import { withFbConsumer } from '@featbit/react-client-sdk';

const Home = ({ flags, fbClient /*, ...otherProps */ }) => {
  // You can call any of the methods from the JavaScript SDK
  // fbClient.identify({...})

  return flags['dev-test-flag'] ? <div>Flag on</div> : <div>Flag off</div>;
};

export default withFbConsumer()(Home);
Using Hooks

The React SDK offers two custom hooks which you can use as an alternative to withFbConsumer:

  • useFlags
  • useFbClient

These functions require React 16.8.0 or later
useFlags and useFbClient use the Hooks API, which requires React version 16.8.0 or later.

useFlags is a custom hook which returns all feature flags. It uses the useContext primitive to access the FeatBit context set up by asyncWithFbProvider or withFbProvider. You still must use the asyncWithFbProvider or the withFbProvider higher-order component at the root of your application to initialize the React SDK and populate the context with fbClient and your flags.

useFbClient is the second custom hook which returns the underlying FeatBit's JavaScript SDK client object. Like the useFlags custom hook, useFbClient also uses the useContext primitive to access the context set up by asyncWithFbProvider or withFbProvider. You still must use the asyncWithFbProvider or the withFbProvider higher-order component to initialize the React SDK to use this custom hook.

Here is an example of how to use those two hooks:

import { useFlags, useFbClient } from '@featbit/react-client-sdk';

const MyComponent = props => {
  const fbClient = useFbClient();

  const { flag1, flag2 } = useFlags();
  // or use
  const flags = useFlags();
  // then use flags.flag1 or flags['flag1'] to reference the flag1 feature flag
  
  return (
    <div>
      <div>1: {flag1}</div>
      <div>2: {flag2}</div>
    </div>
  );
};


export default MyComponent;

Switch user after initialization

If the user is not available during the initialization, you can call the identity() method on fbClient to set the user after initialization.

Switch user in class component

import { withFbConsumer, useFbClient } from '@featbit/react-client-sdk';

class LoginComponent extends React.Component {
    
  handleLogin = async () => {
    const { fbClient } = this.props;
    const user = {}; // use your user object
    await fbClient.identify(user);
  }
    
  render() {
    return (
      <div>
        <button onClick={this.handleLogin}>Login</button>
      </div>
    );
  }
}

export default withFbConsumer()(LoginComponent)

Switch user in function component

import { useFbClient } from '@featbit/react-client-sdk';

const LoginComponent = () => {
  const fbClient = useFbClient();

  handleLogin = async () => {
    const user = {}; // use your user object
    await fbClient.identify(user);
  }
    
  return (
    <div>
      <button onClick={handleLogin}>Login</button>
    </div>
  );
}

Populating the SDK with fallback flag values

As mentioned above, you can use the options.bootstrap option to populate the SDK with default values for your flags. This option is useful when you want to provide default values for your flags before the SDK initializes. If a flag is not available from the SDK, the SDK uses the default value you provide in the bootstrap object.

options: {
  bootstrap: [
    { 
        "id": "my-flag",
        "variation": "on"
    },
    {
      "id": "second-flag",
      "variation": "AlphaGo"
    }
  ]
}

Flag keys

FeatBit primarily identifies feature flags by a key which must contain only alphanumeric characters, dots (.), underscores (_), and dashes (-). These keys are used across all of our APIs as well as in the SDKs to identify flags.

However, JavaScript and React cannot access keys with a dot notation, so the React SDK can change all flag keys to camel case (you need to activate this with the reactOptions.useCamelCaseFlagKeys parameter). A flag with key dev-flag-test is accessible as flags.devFlagTest. This notation flags['dev-flag-test'] should be used if useCamelCaseFlagKeys is disabled, which is by default.

Be aware, by activating useCamelCaseFlagKeys, you would see following problems:

  • It is possible to induce a key collision if there are multiple flag keys which resolve to the same camel-case key. For example, dev-flag-test and dev.flag.test are unique keys, but the React SDK changes them to the same camel-case key.
  • If a flag key contains three or more capital letters in a row, the SDK automatically converts all letters between the first and last capital letter to lower case. For example, the SDK converts a flag with the key devQAFlagTest to devQaFlagTest. If you use devQAFlagTest with the useFlags() hook, the SDK does not find the flag.
  • Because the camel-case functionality is implemented in the React SDK instead of in the underlying JavaScript SDK, the underlying client object and functionality provided by the JavaScript SDK reflect flag keys in their original format. Only React-specific contexts such as your injected props use camel case.

If you've enabled the useCamelCaseFlagKeys option to true, attempting to access a flag using its original key will trigger a warning message in the console: You're attempting to access a flag with its original keyId: xxx, even though useCamelCaseFlagKeys is set to true.

Importing types

In addition to its own bundled types, the React SDK uses types from @featbit/js-client-sdk, these types are re-exported by the React SDK. You can import these types directly from the React SDK

版本与发布记录

@featbit/react-client-sdk 共发布 38 个版本,首次发布于 2024/05/01;过去 12 个月发布了 20 个版本。

版本发布日期距今
4.4.2latest2026/11/0410 天前
4.4.12026/10/3114 天前
4.4.02026/10/3014 天前
4.3.62026/10/1926 天前
4.3.52026/08/172 个月前
4.3.42026/08/172 个月前

关于 @featbit/react-client-sdk 的常见问题

@featbit/react-client-sdk 是什么?

FeatBit client SDK for React

如何安装 @featbit/react-client-sdk?

在项目目录运行 npm install @featbit/react-client-sdk,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^16.6.3 || ^17.0.0 || ^18.0.0 || ^19.0.0)、react-dom(^16.8.4 || ^17.0.0 || ^18.0.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@featbit/react-client-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@featbit/react-client-sdk 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@featbit/react-client-sdk 可以商用吗?

@featbit/react-client-sdk 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@featbit/react-client-sdk 的下载量有多少?

根据 npm 官方下载统计,@featbit/react-client-sdk 在 2026/10/15 – 2026/11/13 这 30 天内被下载 47,034 次,日均约 1,568 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@featbit/react-client-sdk 还在维护吗?

最新版本 4.4.2 发布于 2026/11/04(10 天前);至今共发布 38 个版本,其中过去 12 个月发布了 20 个;首次发布于 2024/05/01。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。