GrowthBook 反应 SDK
增长图书 是一个模块化的地物标记和实验平台.
这是 React 客户端库,允许您在 React 应用程序中评价特征标记并运行实验(A/B测试). 这是薄薄的包装 爪哇语 SDK,所以你可能要先看那些文件 来熟悉基本的课程和方法.
- 无外部依赖关系
- 轻而易举
- 地方目标确定和评价, 不需要 HTTP 请求
- 两者的工程 客户端和服务器端 制作以及 原生反应
- 无闪烁 当运行 A/B 测试时
- 写入 字体 具有广泛测试覆盖面
- 使用您已有的事件跟踪 (GA, 分部, Mixpanel, 定制)
- 进行相互排斥的实验 命名空间
- 远程配置 在不部署新代码的情况下更改特征值
- 运行 视觉实验 不使用 GrowthBook 视觉编辑器写入代码
社区
联合 我们的GrowthBook用户黑社区 如果您需要帮助, 想要聊天, 或者在考虑一个新的功能。 我们是来帮忙的 让GrowthBook变得更好.
安装
yarn add @growthbook/growthbook-react
或者说
npm install --save @growthbook/growthbook-react
快速使用
步骤1:配置您的应用程序
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中有几种使用地标的方法:
地物钩
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} />;
}
}
特性折叠组件
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 钩.
一个例子是在用户登录时更新目标属性:
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。 。 。 .
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。 。 。 .
const gb = new GrowthBook({
apiHost: "https://cdn.growthbook.io",
clientKey: "sdk-abc123",
// Disable background streaming connection
backgroundSync: false,
});
自定义集成
如果你更愿意自己处理网络和缓存逻辑,则可以直接通过一个功能JSON对象. 例如,您可以在 Postgres 中存储特性, 并发送到您的前端, 作为您的应用程序初始的靴子陷阱 API 调用的一部分 .
const gb = new GrowthBook({
features: {
"feature-1": {...},
"feature-2": {...},
"another-feature": {...},
}
})
注意你不必打电话 gb.init() 或者说 gb.loadFeatures()没有什么可以装的 - 所有需要的东西已经传入。 没有向GrowthBook提出任何网络请求.
您可以随时通过调用更新特性 gb.setFeatures() 带有新的 JSON 对象.
等待装入特性
有一个助手组件 <FeaturesReady> 在特性装入之前,您可以制作回落组件。 这既适用于内置取取,也适用于自定义的集成.
<FeaturesReady timeout={500} fallback={<LoadingSpinner />}>
<ComponentThatUsesFeatures />
</FeaturesReady>
timeout是您想要等待特性加载的最大时间( ms) 。 默认是0(没有超时).fallback是在装入特性前要显示的组件。 默认是null。 。 。 .
如果你想要更多的控制, 你可以使用 useGrowthBook() 钩子和 ready 旗帜 :
const gb = useGrowthBook();
if (gb.ready) {
// Do something
}
实验(A/B测试)
为了运行A/B测试,需要设置跟踪回调功能. 每当一个用户被放入实验中,都可以使用此功能来跟踪您分析系统中的曝光事件(Segment,Mixpanel,GA等).
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 不运行.
// 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中,你可以做到这一点:
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用于安全部门改革有两种方法.
仅限安全部门改革
采用这种方法,在提供页面时,对特征标记进行评估一次。 如果特性标记发生变化,用户需要刷新页面才能看到.
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 道具
// 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:
// 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 钩:
// 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.
// 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的行为.
属性
您可以指定当前用户的属性和请求。 这些用于两个方面:
- 特性瞄准(例如付费用户获得一个值,免费用户获得另一个值)
- 指定A/B测试中的持续变异(如用户id"123"总是得到变异B)
下面是一些常用的属性,但对您的应用使用任何有意义的属性.
new GrowthBook({
attributes: {
id: "123",
loggedIn: true,
deviceId: "abc123def456",
company: "acme",
paid: false,
url: "/pricing",
browser: "chrome",
mobile: false,
country: "US",
},
});
更新属性
如果属性发生变化,您可以拨打 setAttributes() 用于更新。 这将完全覆盖任何已存在的属性 。 要进行部分更新,请使用以下模式:
gb.setAttributes({
// Only update the `url` attribute, keep the rest the same
...gb.getAttributes(),
url: "/new-page",
});
特性使用回调
GrowthBook在为用户评价一个特性时可以点出回调. 这可以用来更新"NewRelic"或"DataDog"等第3个政党工具.
new GrowthBook({
onFeatureUsage: (featureKey, result) => {
console.log("feature", featureKey, "has value", result.value);
},
});
注意:如果对同一特性进行多次评价(且数值不变),回调只会被第一次发射.
开发模式
有一个 Growth Book Chrome DevTools 扩展 这可以帮助您调试和测试您的特性标记 .
创建 GrowthBook 实例时, 您必须明确启用 dev 模式
const gb = new GrowthBook({
enableDevMode: true,
});
为了避免将你所有的内部特性旗和实验暴露给用户,我们建议设定为 false 在多数情况下,在生产中.
内置实验
取决于您如何配置特性旗,它们可以在幕后运行 A/B 测试以确定哪些值被分配给用户.
但有时,你想先进行内线实验,而不用先通过一个特征旗. 这个,你可以用到 useExperiment 钩子或更高顺序组件 withRunExperiment数字 :
查看 Javascript SDK 文档 内在实验的所有选项
使用实验钩
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或以上.
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);