# @growthbook/growthbook-react 中文文档

规范地址：https://npmcn.com/package/%40growthbook/growthbook-react/

版本：2\.1\.0
npm 元数据更新时间：2026-11-16T19:46:30.660Z
中文译文更新时间：2026-11-17T01:26:28.496Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40growthbook/growthbook-react
原文对照：https://npmcn.com/package/%40growthbook/growthbook-react/?lang=original
项目主页：https://github.com/growthbook/growthbook#readme
源码仓库：https://github.com/growthbook/growthbook

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：71.5 kB，12 个文件
- 模块格式：ESM + CJS
- TypeScript 类型：包内自带
- Node.js 要求：\>=10
- 运行依赖：1 个
- peer 依赖：react ^16\.8\.0-0 \|\| ^17\.0\.0-0 \|\| ^18\.0\.0-0 \|\| ^19\.0\.0-0
- 首次发布：2021-03-31T18:41:20.055Z
- 最新版本发布：2026-11-16T19:46:30.453Z
- 近 30 天下载量：2031570（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：59（近 12 个月 7 个）

## 中文简介

[增长图书](https://www.growthbook.io/) 是一个模块化的地物标记和实验平台.

## 安装

```sh
npm install @growthbook/growthbook-react
```

也可以使用：`pnpm add @growthbook/growthbook-react`、`yarn add @growthbook/growthbook-react`、`bun add @growthbook/growthbook-react`

## README

# GrowthBook 反应 SDK

[增长图书](https://www.growthbook.io/) 是一个模块化的地物标记和实验平台.

这是 React 客户端库,允许您在 React 应用程序中评价特征标记并运行实验(A/B测试). 这是薄薄的包装 [爪哇语 SDK](https://docs.growthbook.io/lib/js),所以你可能要先看那些文件 来熟悉基本的课程和方法.

![Build Status](https://github.com/growthbook/growthbook/workflows/CI/badge.svg) ![GZIP Size](https://img.shields.io/badge/gzip%20size-7.84KB-informational) ![NPM Version](https://img.shields.io/npm/v/@growthbook/growthbook-react)

-   **无外部依赖关系**
-   **轻而易举**
-   地方目标确定和评价, **不需要 HTTP 请求**
-   两者的工程 **客户端和服务器端** 制作以及 **原生反应**
-   **无闪烁** 当运行 A/B 测试时
-   写入 **字体** 具有广泛测试覆盖面
-   **使用您已有的事件跟踪** (GA, 分部, Mixpanel, 定制)
-   进行相互排斥的实验 **命名空间**
-   **远程配置** 在不部署新代码的情况下更改特征值
-   运行 **视觉实验** 不使用 GrowthBook 视觉编辑器写入代码

## 社区

联合 [我们的GrowthBook用户黑社区](https://slack.growthbook.io/?ref=react-readme) 如果您需要帮助, 想要聊天, 或者在考虑一个新的功能。 我们是来帮忙的 让GrowthBook变得更好.

## 安装

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

或者说

```
npm install --save @growthbook/growthbook-react
```

## 快速使用

### 步骤1:配置您的应用程序

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

// Create a GrowthBook instance
const gb = new GrowthBook({
  apiHost: "https://cdn.growthbook.io",
  clientKey: "sdk-abc123",
  // Enable easier debugging during development
  enableDevMode: true,
  // Update the instance in realtime as features change in GrowthBook
  subscribeToChanges: true,
  // Only required for A/B testing
  // Called every time a user is put into an experiment
  trackingCallback: (experiment, result, user) => {
    console.log("Experiment Viewed", {
      experimentId: experiment.key,
      variationId: result.key,
      attributes: user?.attributes,
    });
  },
});
gb.init();

export default function App() {
  useEffect(() => {
    // Set user attributes for targeting (from cookie, auth system, etc.)
    gb.setAttributes({
      id: user.id,
      company: user.company,
    });
  }, [user]);

  return (
    <GrowthBookProvider growthbook={gb}>
      <OtherComponent />
    </GrowthBookProvider>
  );
}
```

### 第2步: 开始显示功能!

GrowthBook中有几种使用地标的方法:

#### 地物钩

```tsx
import { useFeatureValue, useFeatureIsOn } from "@growthbook/growthbook-react";

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

  // String/Number/JSON features with a fallback value
  const buttonColor = useFeatureValue("login-button-color", "blue");

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

#### 特性折叠组件

```tsx
import { IfFeatureEnabled, FeatureString } from "@growthbook/growthbook-react";

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

#### 使用浏览书钩

如果您出于任何原因需要低水平访问 GrowthBook 实例, 您可以使用 `useGrowthBook` 钩.

一个例子是在用户登录时更新目标属性:

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

export default function Auth() {
  const growthbook = useGrowthBook();

  const user = useUser();
  useEffect(() => {
    if (!user || !growthbook) return;
    growthbook.setAttributes({
      loggedIn: true,
      id: user.id,
      company: user.company,
      isPro: user.plan === "pro"
    })
  }, [user, growthbook])

  ...
}
```

## 装入特性

为了让GrowthBook SDK发挥作用,它需要有GrowthBook API的特征定义. 有两种方法将这些数据输入SDK.

### 内建抓取和缓存

如果你通过一个 `apiHost` 财务报告和审定财务报表 `clientKey` 输入 GrowthBook 构建器,它将自动为您处理网络请求、缓存、重试逻辑等。 如果您的特性有效载荷被加密, 您也可以在 `decryptionKey`。 。 。 .

```ts
const gb = new GrowthBook({
  apiHost: "https://cdn.growthbook.io",
  clientKey: "sdk-abc123",
  // Only required if you have feature encryption enabled in GrowthBook
  decryptionKey: "key_abc123",
  // Update the instance in realtime as features change in GrowthBook (default: false)
  subscribeToChanges: true,
});

// Wait for features to be downloaded
await gb.init({
  // If the network request takes longer than this (in milliseconds), continue
  // Default: `0` (no timeout)
  timeout: 2000,
});
```

在装入特性之前,所有特性都会评估到 `null`。如果您在应用程序中可以使用一个潜在的闪光器(从 `null` 你可以打给 `loadFeatures` 不等待结果.

如果你想随时刷新功能(例如当导航事件发生时),可以拨打 `gb.refreshFeatures()`。 。 。 .

#### 流出更新

默认情况下,SDK会使用Server-Sent Eventions(SSE)打开一串流接通,在GrowthBook中更改时实时接收功能更新. 它只在GrowthBook Cloud上或运行GrowthBook代理服务器时被支持.

如果您想要禁用流流更新( 例如在 GrowthBook Cloud 上限制 API 使用) , 您可以设置 `backgroundSync` 改为 `false`。 。 。 .

```ts
const gb = new GrowthBook({
  apiHost: "https://cdn.growthbook.io",
  clientKey: "sdk-abc123",

  // Disable background streaming connection
  backgroundSync: false,
});
```

### 自定义集成

如果你更愿意自己处理网络和缓存逻辑,则可以直接通过一个功能JSON对象. 例如,您可以在 Postgres 中存储特性, 并发送到您的前端, 作为您的应用程序初始的靴子陷阱 API 调用的一部分 .

```ts
const gb = new GrowthBook({
  features: {
    "feature-1": {...},
    "feature-2": {...},
    "another-feature": {...},
  }
})
```

注意你不必打电话 `gb.init()` 或者说 `gb.loadFeatures()`没有什么可以装的 - 所有需要的东西已经传入。 没有向GrowthBook提出任何网络请求.

您可以随时通过调用更新特性 `gb.setFeatures()` 带有新的 JSON 对象.

### 等待装入特性

有一个助手组件 `<FeaturesReady>` 在特性装入之前,您可以制作回落组件。 这既适用于内置取取,也适用于自定义的集成.

```jsx
<FeaturesReady timeout={500} fallback={<LoadingSpinner />}>
  <ComponentThatUsesFeatures />
</FeaturesReady>
```

-   `timeout` 是您想要等待特性加载的最大时间( ms) 。 默认是 `0` (没有超时).
-   `fallback` 是在装入特性前要显示的组件。 默认是 `null`。 。 。 .

如果你想要更多的控制, 你可以使用 `useGrowthBook()` 钩子和 `ready` 旗帜 :

```ts
const gb = useGrowthBook();

if (gb.ready) {
  // Do something
}
```

## 实验(A/B测试)

为了运行A/B测试,需要设置跟踪回调功能. 每当一个用户被放入实验中,都可以使用此功能来跟踪您分析系统中的曝光事件(Segment,Mixpanel,GA等).

```js
const gb = new GrowthBook({
  apiHost: "https://cdn.growthbook.io",
  clientKey: "sdk-abc123",
  trackingCallback: (experiment, result, user) => {
    // Example using Segment
    analytics.track("Experiment Viewed", {
      experimentId: experiment.key,
      variationId: result.key,
      attributes: user?.attributes,
    });
  },
});
```

从1.7.0版本开始,回调收到第三个版本 `user` 参数: a `TrackingUserContext` 内含 `attributes` 和可选 `url` 在评估实验时使用。 我们建议从这一论点中记录属性,从而使曝光事件始终反映用于确定目标和分配的属性GrowthBook.

同样的追踪回调用于特性旗实验和视觉编辑器实验.

### 地物旗实验

评价特性(例如: `useFeatureValue` 或者说 `useFeatureIsOn`) 输入特征旗实验;即何时 `trackingCallback` 运行。 如果它们不包含,你仍然得到一个值和 `trackingCallback` 不运行.

```js
// If this has an active experiment and the user is included,
// it will call trackingCallback automatically
useFeatureIsOn("new-signup-form");
```

如果实验来自一个特征规则, `result.featureId` 在"追踪Callback"中将包含特性ID,这可能对跟踪/博客目的有用.

### 视觉编辑器实验

通过GrowthBook视觉编辑器创建的实验,一旦达到目标条件,将自动运行.

**说明**:视觉编辑器实验只在网页浏览器环境中支持. 它们不会在 React Natural 中运行,也不会在服务器侧面渲染(SSR)时运行.

如果您在单页 App( SPA) 中使用了 SDK, 您需要让 GrowthBook 实例知道 URL 何时改变, 这样活动实验就可以相应更新 .

例如,在Next.js中,你可以做到这一点:

```js
function updateGrowthBookURL() {
  gb.setURL(window.location.href);
}

export default function MyApp() {
  // Subscribe to route change events and update GrowthBook
  const router = useRouter();
  useEffect(() => {
    router.events.on("routeChangeComplete", updateGrowthBookURL);
    return () => router.events.off("routeChangeComplete", updateGrowthBookURL);
  }, []);

  // ...
}
```

## 服务器侧面渲染( SSR)

这个SDK完全支持服务器侧渲染. 以下例子使用Next.js,但其他框架应当类似.

使用GrowthBook用于安全部门改革有两种方法.

### 仅限安全部门改革

采用这种方法,在提供页面时,对特征标记进行评估一次。 如果特性标记发生变化,用户需要刷新页面才能看到.

```js
export async function getServerSideProps(context) {
  // Create a GrowthBook instance and load features from the API
  const gb = new GrowthBook({
    apiHost: "https://cdn.growthbook.io",
    clientKey: "sdk-abc123",
    attributes: {
      // TODO: get more targeting attributes from request context
      id: context.req.cookies.DEVICE_ID,
    },
  });
  await gb.init();

  return {
    props: {
      title: gb.getFeatureValue("site-title", "fallback"),
      showBanner: gb.isOn("sale-banner"),
    },
  };
}

export default function MyPage({ title, showBanner }) {
  return (
    <div>
      <h1>{title}</h1>
      {showBanner && <div className="sale">There's a Sale!</div>}
    </div>
  );
}
```

### 混合( SSR + 客户端)

通过这种方法,您会使用客户端钩和组件(例如. `useFeatureValue`),并简单地使用SSR来确保初始负载已经具备API的最新特性.

您可以得到客户端渲染的好处( 交互性, 实时特性标记更新) , 再加上 SSR 的好处( 不闪烁, 改进的 SEO) 。 不过,这确实需要多做一些工作.

首先, 创建一个帮助函数, 从收到的请求中生成 GrowthBook SSR 道具

```js
// util/gb-server.js
import { getGrowthBookSSRData } from "@growthbook/growthbook-react";

export async function generateGrowthBookSSRProps(context) {
  return getGrowthBookSSRData({
    apiHost: process.env.NEXT_PUBLIC_GROWTHBOOK_API_HOST,
    clientKey: process.env.NEXT_PUBLIC_GROWTHBOOK_CLIENT_KEY,
    attributes: {
      // TODO: get more targeting attributes from request context
      id: context.req.cookies.DEVICE_ID,
    },
  });
}
```

然后,跟客户端的渲染一样 将您的应用包入 GrowthBook Provider:

```jsx
// pages/_app.jsx
import { useEffect } from "react";
import { GrowthBook, GrowthBookProvider } from "@growthbook/growthbook-react";

// Create a client-side GrowthBook instance
const gb = new GrowthBook({
  apiHost: "https://cdn.growthbook.io",
  clientKey: "sdk-abc123",
  // Enable easier debugging of feature flags during development
  enableDevMode: true,
  // Update the instance in realtime as features change in GrowthBook
  subscribeToChanges: true,
});
gb.init();

export default function App() {
  useEffect(() => {
    // Set user attributes for targeting (use the same values as SSR when possible)
    gb.setAttributes({
      id: user.id,
    });
  }, [user]);

  return (
    <GrowthBookProvider growthbook={gb}>
      <OtherComponent />
    </GrowthBookProvider>
  );
}
```

现在,在一个服务器提供的页面上, 打电话给你的助手,然后把它传到 `useGrowthBookSSR` 钩:

```jsx
// pages/server.jsx
import MyComponent from "../components/MyComponent";
import { generateGrowthBookSSRProps } from "../util/gb-server";
import { useGrowthBookSSR } from "@growthbook/growthbook-react";

export async function getServerSideProps(context) {
  const gbData = await generateGrowthBookSSRProps(context);
  return {
    props: {
      gbData,
    },
  };
}

export default function ServerPage({ gbData }) {
  // This is required once at the top of the SSR page
  useGrowthBookSSR(gbData);

  return <MyComponent />;
}
```

最后,在其余的应用中,使用客户端的钩子和组件,就像如果你没有使用SS.

```jsx
// components/MyComponent.jsx
export default function MyComponent() {
  // Boolean on/off features
  const newLogin = useFeatureIsOn("new-login-form");

  // String/Number/JSON features with a fallback value
  const buttonColor = useFeatureValue("login-button-color", "blue");

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

如果您不使用 SSR, 初始渲染会使用功能的倒置值, 然后在回放水合页面后, 适当的值会弹出, 可能导致缓慢连接的闪烁。 这种方法通过确保特征从一开始就具有适当的价值来解决了这个问题.

## API 参考

有许多配置选项和设置可以控制GrowthBook的行为.

### 属性

您可以指定当前用户的属性和请求。 这些用于两个方面:

1.  特性瞄准(例如付费用户获得一个值,免费用户获得另一个值)
2.  指定A/B测试中的持续变异(如用户id"123"总是得到变异B)

下面是一些常用的属性,但对您的应用使用任何有意义的属性.

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

#### 更新属性

如果属性发生变化,您可以拨打 `setAttributes()` 用于更新。 这将完全覆盖任何已存在的属性 。 要进行部分更新,请使用以下模式:

```js
gb.setAttributes({
  // Only update the `url` attribute, keep the rest the same
  ...gb.getAttributes(),
  url: "/new-page",
});
```

### 特性使用回调

GrowthBook在为用户评价一个特性时可以点出回调. 这可以用来更新"NewRelic"或"DataDog"等第3个政党工具.

```ts
new GrowthBook({
  onFeatureUsage: (featureKey, result) => {
    console.log("feature", featureKey, "has value", result.value);
  },
});
```

注意:如果对同一特性进行多次评价(且数值不变),回调只会被第一次发射.

### 开发模式

有一个 [Growth Book Chrome DevTools 扩展](https://chrome.google.com/webstore/detail/growthbook-devtools/opemhndcehfgipokneipaafbglcecjia) 这可以帮助您调试和测试您的特性标记 .

创建 GrowthBook 实例时, 您必须明确启用 dev 模式

```js
const gb = new GrowthBook({
  enableDevMode: true,
});
```

为了避免将你所有的内部特性旗和实验暴露给用户,我们建议设定为 `false` 在多数情况下,在生产中.

### 内置实验

取决于您如何配置特性旗,它们可以在幕后运行 A/B 测试以确定哪些值被分配给用户.

但有时,你想先进行内线实验,而不用先通过一个特征旗. 这个,你可以用到 `useExperiment` 钩子或更高顺序组件 `withRunExperiment`数字 :

查看 [Javascript SDK 文档](https://docs.growthbook.io/lib/js) 内在实验的所有选项

#### 使用实验钩

```tsx
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>;
}
```

#### 与 Run 实验( 类组件)

**说明:** 这个库在内部使用钩子,所以仍然需要回放16.8或以上.

```tsx
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);
```

## 实例

-   [原生反应](https://github.com/growthbook/examples/tree/main/react-native-cli)

## 常见问题

### @growthbook/growthbook-react 是什么？

增长图书 是一个模块化的地物标记和实验平台\.

### 如何安装 @growthbook/growthbook-react？

在项目目录运行 npm install @growthbook/growthbook-react，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：react（^16\.8\.0-0 \|\| ^17\.0\.0-0 \|\| ^18\.0\.0-0 \|\| ^19\.0\.0-0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @growthbook/growthbook-react 支持 TypeScript 吗？

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

### @growthbook/growthbook-react 支持 ESM 还是 CommonJS？

同时提供 ES Module 与 CommonJS 入口，import 和 require\(\) 都可以使用，打包工具会自动选择合适的版本。

### @growthbook/growthbook-react 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=10。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### @growthbook/growthbook-react 可以商用吗？

@growthbook/growthbook-react 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @growthbook/growthbook-react 的下载量有多少？

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

### @growthbook/growthbook-react 还在维护吗？

最新版本 2\.1\.0 发布于 2026/11/17（今天）；至今共发布 59 个版本，其中过去 12 个月发布了 7 个；首次发布于 2021/04/01。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

