> For the complete documentation index, see [llms.txt](https://docs.reflag.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.reflag.com/supported-languages/react-sdk.md). Agents can also search and read this documentation through its [MCP server](https://docs.reflag.com/~gitbook/mcp).

# React SDK

React client side library for [Reflag.com](https://reflag.com)

Reflag supports flag toggling, tracking flag usage, [requesting feedback](#userequestfeedback) on features, and [multivariate flags](#multivariate-flags) that return strings, numbers or JSON objects.

The Reflag React SDK comes with a [built-in toolbar](https://docs.reflag.com/supported-languages/browser-sdk.md#toolbar) which appears on `localhost` by default.

This page covers React SDK v2. For the legacy v1 SDK, see the [v1 docs](https://docs.reflag.com/legacy-sdks/v1/react-sdk.md) and the [upgrade guide](https://docs.reflag.com/supported-languages/migrating-from-v1.md).

## Install <a href="#install" id="install"></a>

Install via npm:

```shell
npm i @reflag/react-sdk
```

## Get started <a href="#get-started" id="get-started"></a>

### 1. Add the `ReflagProvider` context provider <a href="#id-1-add-the-reflagprovider-context-provider" id="id-1-add-the-reflagprovider-context-provider"></a>

Add the `ReflagProvider` context provider to your application:

**Example:**

```tsx
import { ReflagProvider } from "@reflag/react-sdk";

<ReflagProvider
  publishableKey="{YOUR_PUBLISHABLE_KEY}"
  context={{
    company: { id: "acme_inc", plan: "pro" },
    user: { id: "john doe" },
  }}
  loadingComponent={<Loading />}
>
  {/* children here are shown when loading finishes or immediately if no `loadingComponent` is given */}
</ReflagProvider>;
```

### 2. Create a new flag and set up type safety <a href="#id-2-create-a-new-flag-and-set-up-type-safety" id="id-2-create-a-new-flag-and-set-up-type-safety"></a>

Install the Reflag CLI:

```shell
npm i --save-dev @reflag/cli
```

Run `npx reflag new` to create your first flag! On the first run, it will sign into Reflag and set up type generation for your project:

```shell
❯ npx reflag new
Opened web browser to facilitate login: https://app.reflag.com/api/oauth/cli/authorize

Welcome to ◪ Reflag!

? Where should we generate the types? gen/flags.d.ts
? What is the output format? react
✔ Configuration created at reflag.config.json.

Creating flag for app Slick app.
? New flag name: Huddle
? New flag key: huddle
✔ Created flag Huddle with key huddle (https://app.reflag.com/features/huddles)
✔ Generated react types in gen/flags.d.ts.
```

> \[!Note] By default, types will be generated in `gen/flags.d.ts`. The default `tsconfig.json` file `include`s this file by default, but if your `tsconfig.json` is different, make sure the file is covered in the `include` property.

### 3. Use `useFlag(<flagKey>)` to get flag status <a href="#id-3-use-useflagflagkey-to-get-flag-status" id="id-3-use-useflagflagkey-to-get-flag-status"></a>

Using the `useFlag` hook from your components lets you toggle flags on/off, and `useTrack` lets you track flag usage:

**Example:**

```tsx
import { useFlag, useTrack } from "@reflag/react-sdk";

function StartHuddleButton() {
  const isEnabled = useFlag("huddle"); // boolean indicating if the flag is enabled
  const track = useTrack(); // track usage of the flag

  if (!isEnabled) {
    return null;
  }

  return <button onClick={() => track("huddle")}>Start huddle!</button>;
}
```

`useFlag` can help you do much more. See a full example for `useFlag` [see below](#useflag).

## Setting context <a href="#setting-context" id="setting-context"></a>

Reflag determines which flags are active for a given `user`, `company`, or `other` context. You can pass these to the `ReflagProvider` using the `context` prop.

### Using the `context` prop <a href="#using-the-context-prop" id="using-the-context-prop"></a>

```tsx
<ReflagProvider
  publishableKey={YOUR_PUBLISHABLE_KEY}
  context={{
    user: { id: "user_123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company_123", name: "Acme, Inc" },
    other: { source: "web" },
  }}
>
  <LoadingReflag>
    {/* children here are shown when loading finishes */}
  </LoadingReflag>
</ReflagProvider>
```

### Legacy individual props (deprecated) <a href="#legacy-individual-props-deprecated" id="legacy-individual-props-deprecated"></a>

For backward compatibility, you can still use individual props, but these are deprecated and will be removed in the next major version:

```tsx
<ReflagProvider
  publishableKey={YOUR_PUBLISHABLE_KEY}
  user={{ id: "user_123", name: "John Doe", email: "john@acme.com" }}
  company={{ id: "company_123", name: "Acme, Inc" }}
  otherContext={{ source: "web" }}
>
  <LoadingReflag>
    {/* children here are shown when loading finishes */}
  </LoadingReflag>
</ReflagProvider>
```

> \[!Important] The `user`, `company`, and `otherContext` props are deprecated. Use the `context` prop instead, which provides the same functionality in a more structured way.

### Context requirements <a href="#context-requirements" id="context-requirements"></a>

If you supply `user` or `company` objects, they must include at least the `id` property otherwise they will be ignored in their entirety. In addition to the `id`, you must also supply anything additional that you want to be able to evaluate flag targeting rules against. Attributes which are not properties of the `user` or `company` can be supplied using the `other` property.

Attributes cannot be nested (multiple levels) and must be either strings, numbers or booleans. A number of special attributes exist:

* `name` -- display name for `user`/`company`,
* `email` -- the email of the user,
* `avatar` -- the URL for `user`/`company` avatar image.

To retrieve a flag's value, use the `useFlag(key: string)` hook (described in a section below).

Note that each `useFlag()` read automatically generates a `check` event.

## React Native <a href="#react-native" id="react-native"></a>

For React Native, use `@reflag/react-native-sdk`, which is a thin wrapper around `@reflag/react-sdk` and wires up AsyncStorage by default.

An Expo example app lives at `packages/react-native-sdk/dev/expo`.

## Multivariate flags <a href="#multivariate-flags" id="multivariate-flags"></a>

Multivariate flags are a dynamic and flexible approach to configuring flag behavior outside of your app – without needing to re-deploy it.

Instead of a Boolean, a multivariate flag returns one of several values, which can be strings, numbers or JSON objects. The values are managed from within Reflag, similar to the way access to flags is managed, and different users/companies can get different values.

### Get started with multivariate flags <a href="#get-started-with-multivariate-flags" id="get-started-with-multivariate-flags"></a>

1. Update your flag definitions:

```typescript
import "@reflag/react-sdk";

// Define your flags by extending the `Flags` interface in @reflag/react-sdk
declare module "@reflag/react-sdk" {
  interface Flags {
    huddle: boolean;
    // a multivariate flag whose values are objects
    "huddle-settings": {
      maxTokens: number;
      model: string;
    };
  }
}
```

2. Read the flag with a default:

```ts
const settings = useFlag("huddle-settings", {
  maxTokens: 1000,
  model: "gpt-3.5",
});

// settings: { maxTokens: 10000, model: "gpt-3.5-beta1" }
```

The default sets the return type. `useFlag()` returns the default while flags load, or if the flag is missing or has a different JSON type, so make sure your default is a value your application can use. Pass `null` as the default to accept any JSON value, then check its type before using it. The SDK doesn't check object fields or fill in missing fields from your default.

Without a default, `useFlag()` expects a Boolean and returns `false` if the flag is missing or isn't a Boolean.

Note that, similar to Boolean flags, each read of a multivariate flag automatically generates a `check` event.

Remote config from v1 isn't converted automatically. Move each remote config to a multivariate flag; see [Migrating from v1](#migrating-from-v1).

## Toolbar <a href="#toolbar" id="toolbar"></a>

The Reflag Toolbar is great for toggling flags on/off for yourself to ensure that everything works both when a flag is on and when it's off.

<img src="https://github.com/user-attachments/assets/61492915-0d30-446d-a163-3eb16d9024b2" alt="Toolbar" height="265" width="310">

The toolbar will automatically appear on `localhost`. However, it can also be incredibly useful in production. You have full control over when it appears through the `toolbar` configuration option passed to the ReflagProvider.

You can pass a simple boolean to force the toolbar to appear/disappear:

```ts
<ReflagProvider
  ...
  // show the toolbar even in production if the user is an internal/admin user
  toolbar={user?.isInternal}
  ...
});
```

## Server-side rendering and bootstrapping <a href="#server-side-rendering-and-bootstrapping" id="server-side-rendering-and-bootstrapping"></a>

For server-side rendered applications, you can render immediately with pre-fetched flag data using the `ReflagBootstrappedProvider`.

Bootstrapping is also the recommended setup if you want the most resilient feature flag architecture in React. The client renders immediately from flags provided by your server instead of making its initial render depend on a request to Reflag.

If you want "bullet proof feature flags" in a React application, use React bootstrapping together with `flagsFallbackProvider` in the Node SDK. The fallback provider helps your server start with the latest saved snapshot if it cannot reach Reflag during initialization, and bootstrapping gives the React client server-provided flags for its first render.

### Using `ReflagBootstrappedProvider` <a href="#using-reflagbootstrappedprovider" id="using-reflagbootstrappedprovider"></a>

The `<ReflagBootstrappedProvider>` component is a specialized version of `ReflagProvider` designed for server-side rendering, preloaded flag scenarios, and high-reliability setups. It uses pre-fetched evaluated state for the initial render, resulting in faster initial page loads, better SSR compatibility, and a more resilient startup path for React applications.

```tsx
import { useState, useEffect } from "react";
import { BootstrappedFlags } from "@reflag/react-sdk";

interface BootstrapData {
  user: User;
  flags: BootstrappedFlags;
}

function useBootstrap() {
  const [data, setData] = useState<BootstrapData | null>(null);

  useEffect(() => {
    fetch("/bootstrap")
      .then((res) => res.json())
      .then(setData);
  }, []);

  return data;
}

// Usage in your app
function App() {
  const data = useBootstrap();

  if (!data) return <Loading />;

  return (
    <AuthProvider user={data.user}>
      <ReflagBootstrappedProvider
        publishableKey="your-publishable-key"
        flags={data.flags}
      >
        <Router />
      </ReflagBootstrappedProvider>
    </AuthProvider>
  );
}
```

### Server-side endpoint setup <a href="#server-side-endpoint-setup" id="server-side-endpoint-setup"></a>

Create an endpoint that provides bootstrap data to your client application:

```typescript
// server.js or your Express app
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";

const reflagClient = new ReflagNodeClient({
  secretKey: process.env.REFLAG_SECRET_KEY,
});
await reflagClient.initialize();

app.get("/bootstrap", (req, res) => {
  const user = getUser(req); // Get user from your auth system
  const company = getCompany(req); // Get company from your auth system

  // Include only attributes the browser may see
  const flags = reflagClient.getFlagsForBootstrap({
    user: { id: user.id, name: user.name, email: user.email },
    company: { id: company.id, name: company.name, plan: company.plan },
    other: { source: "web" },
  });

  res.status(200).json({
    user,
    flags,
  });
});
```

The `flags` object returned by `getFlagsForBootstrap()` contains the full bootstrapped state package:

* `protocolVersion`: the bootstrap format version
* `context`: the evaluation context used on the server
* `flags`: the evaluated raw flags
* `flagStateVersion`: an optional version used to avoid redundant live-update refreshes immediately after bootstrapping

`getFlagsForBootstrap()` only includes flags that are marked as not secret (`secret: false`). Secret flags can still be read on the server. Because the browser can read the bootstrapped context, include only browser-safe attributes in it.

Use `@reflag/node-sdk` v2 to produce the bootstrap data. The React SDK v2 doesn't accept bootstrap data from Node SDK v1.

### Next.js Page Router SSR example <a href="#nextjs-page-router-ssr-example" id="nextjs-page-router-ssr-example"></a>

For Next.js applications using server-side rendering, you can pre-fetch flags in `getServerSideProps`:

```typescript
// pages/index.tsx
import { GetServerSideProps } from "next";
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";
import { ReflagBootstrappedProvider, BootstrappedFlags, useFlag, useTrack } from "@reflag/react-sdk";

interface PageProps {
  bootstrapData: BootstrappedFlags;
}

// Create one client per server process and reuse it across requests
const serverClient = new ReflagNodeClient({
  secretKey: process.env.REFLAG_SECRET_KEY
});
const serverClientReady = serverClient.initialize();

export const getServerSideProps: GetServerSideProps = async (context) => {
  await serverClientReady;

  const user = await getUserFromSession(context.req);
  const company = await getCompanyFromUser(user);

  // Include only attributes the browser may see
  const bootstrapData = serverClient.getFlagsForBootstrap({
    user: { id: user.id, name: user.name, email: user.email },
    company: { id: company.id, name: company.name, plan: company.plan },
    other: { page: "homepage" }
  });

  return { props: { bootstrapData } };
};

export default function HomePage({ bootstrapData }: PageProps) {
  return (
    <ReflagBootstrappedProvider
      publishableKey={process.env.NEXT_PUBLIC_REFLAG_PUBLISHABLE_KEY}
      flags={bootstrapData}
    >
      <HuddleFeature />
    </ReflagBootstrappedProvider>
  );
}

function HuddleFeature() {
  const isEnabled = useFlag("huddle");
  const settings = useFlag("huddle-settings", {
    maxParticipants: 10,
    videoQuality: "standard",
  });
  const track = useTrack();

  if (!isEnabled) return null;

  return (
    <div>
      <h2>Start a Huddle</h2>
      <p>Max participants: {settings.maxParticipants}</p>
      <p>Video quality: {settings.videoQuality}</p>
      <button onClick={() => track("huddle")}>Start Huddle</button>
    </div>
  );
}
```

This approach eliminates loading states and removes the initial render's dependency on the flags API.

### Next.js App Router example <a href="#nextjs-app-router-example" id="nextjs-app-router-example"></a>

For Next.js applications using the App Router (Next.js 13+), you can pre-fetch flags in Server Components and pass them to client components:

```typescript
// app/layout.tsx (Server Component)
import { ReflagClient as ReflagNodeClient } from "@reflag/node-sdk";
import { ClientProviders } from "./providers";

// Create one client per server process and reuse it across requests
const serverClient = new ReflagNodeClient({
  secretKey: process.env.REFLAG_SECRET_KEY!
});
const serverClientReady = serverClient.initialize();

async function getBootstrapData() {
  await serverClientReady;

  // In a real app, you'd get user/company from your auth system
  const bootstrapData = serverClient.getFlagsForBootstrap({
    user: { id: "user123", name: "John Doe", email: "john@acme.com" },
    company: { id: "company456", name: "Acme Inc", plan: "enterprise" },
    other: { source: "web" }
  });

  return bootstrapData;
}

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  const bootstrapData = await getBootstrapData();

  return (
    <html lang="en">
      <body>
        <ClientProviders bootstrapData={bootstrapData}>
          {children}
        </ClientProviders>
      </body>
    </html>
  );
}
```

```typescript
// app/providers.tsx (Client Component)
"use client";

import { ReflagBootstrappedProvider, BootstrappedFlags } from "@reflag/react-sdk";

interface ClientProvidersProps {
  children: React.ReactNode;
  bootstrapData: BootstrappedFlags;
}

export function ClientProviders({ children, bootstrapData }: ClientProvidersProps) {
  return (
    <ReflagBootstrappedProvider
      publishableKey={process.env.NEXT_PUBLIC_REFLAG_PUBLISHABLE_KEY!}
      flags={bootstrapData}
    >
      {children}
    </ReflagBootstrappedProvider>
  );
}
```

```typescript
// app/page.tsx (Server Component)
import { HuddleFeature } from "./huddle-feature";

export default function HomePage() {
  return (
    <main>
      <h1>My App</h1>
      <HuddleFeature />
    </main>
  );
}
```

```typescript
// app/huddle-feature.tsx (Client Component)
"use client";

import { useFlag, useTrack } from "@reflag/react-sdk";

export function HuddleFeature() {
  const isEnabled = useFlag("huddle");
  const settings = useFlag("huddle-settings", {
    maxParticipants: 10,
    videoQuality: "standard",
  });
  const track = useTrack();

  if (!isEnabled) return null;

  return (
    <div>
      <h2>Start a Huddle</h2>
      <p>Max participants: {settings.maxParticipants}</p>
      <p>Video quality: {settings.videoQuality}</p>
      <button onClick={() => track("huddle")}>Start Huddle</button>
    </div>
  );
}
```

This App Router approach leverages Server Components for server-side flag fetching while using Client Components only where React state and hooks are needed.

## `<ReflagClientProvider>` component <a href="#reflagclientprovider-component" id="reflagclientprovider-component"></a>

The `<ReflagClientProvider>` is a lower-level component that accepts a `ReflagClient` instance. This is useful for advanced use cases where you need full control over client initialization or want to share a client instance across multiple parts of your application.

In most cases you should initialize the client before rendering this provider. If you pass an idle client, a `useFlagSuspense()` call can initialize the client on demand; otherwise, you must initialize the client yourself.

### Usage <a href="#usage" id="usage"></a>

```tsx
import { ReflagClient } from "@reflag/browser-sdk";
import { ReflagClientProvider } from "@reflag/react-sdk";

// Initialize the client yourself
const client = new ReflagClient({
  publishableKey: "your-publishable-key",
  user: { id: "user123", name: "John Doe" },
  company: { id: "company456", name: "Acme Inc" },
  // ... other configuration options
});

// Initialize the client
await client.initialize();

function App() {
  return (
    <ReflagClientProvider client={client} loadingComponent={<Loading />}>
      <Router />
    </ReflagClientProvider>
  );
}
```

### Props <a href="#props" id="props"></a>

The `ReflagClientProvider` accepts the following props:

* `client`: A `ReflagClient` instance. Prefer passing an already-initialized client; idle clients are initialized on demand only by `useFlagSuspense()` calls.
* `loadingComponent`: Optional React component to show while the client is initializing (same as `ReflagProvider`)
* `suspense`: Optional. Set to `true` to make `useOptInFlags()` suspend while opt-in metadata is loading. To suspend flag reads, use `useFlagSuspense()`.

> \[!Note] Most applications should use `ReflagProvider` or `ReflagBootstrappedProvider` instead of `ReflagClientProvider`. Only use this component when you need the advanced control it provides.

## `<ReflagProvider>` component <a href="#reflagprovider-component" id="reflagprovider-component"></a>

The `<ReflagProvider>` initializes the Reflag SDK, fetches flags and starts listening for automated feedback survey events. The component can be configured using a number of props:

* `publishableKey` is used to connect the provider to an *environment* on Reflag. Find your `publishableKey` under [environment settings](https://app.reflag.com/env-current/settings/app-environments) in Reflag,
* `context` (recommended): An object containing `user`, `company`, and `other` properties that make up the evaluation context used to determine if a flag is enabled or not. `company` and `user` contexts are automatically transmitted to Reflag servers so the Reflag app can show you which companies have access to which flags etc.
* `company`, `user` and `other` (deprecated): Individual props for context. These are deprecated in favor of the `context` prop and will be removed in the next major version.

  > \[!Note] If you specify `company` and/or `user` they must have at least the `id` property, otherwise they will be ignored in their entirety. You should also supply anything additional you want to be able to evaluate flag targeting against,
* `timeoutMs`: Timeout in milliseconds when fetching flags from the server.
* `staleWhileRevalidate`: If set to `true`, stale flags will be returned while refetching flags in the background.
* `expireTimeMs`: If set, flags will be cached between page loads for this duration (in milliseconds).
* `staleTimeMs`: Maximum time (in milliseconds) that stale flags will be returned if `staleWhileRevalidate` is true and new flags cannot be fetched.
* `offline`: Provide this option when testing or in local development environments to avoid contacting Reflag servers.
* `loadingComponent` lets you specify an React component to be rendered instead of the children while the Reflag provider is initializing. If you want more control over loading screens, `useIsLoading()` returns `isLoading` which you can use to customize the loading experience.
* `suspense`: Set to `true` to make `useOptInFlags()` suspend while required opt-in metadata is loading. Flag reads with `useFlag()` never suspend; use `useFlagSuspense()` to suspend them. Wrap components that suspend in React `<Suspense>` boundaries and omit `loadingComponent` if you want Suspense fallbacks to control loading UI.
* `enableTracking`: Set to `false` to stop sending tracking events and user/company updates to Reflag. Useful when you're impersonating a user (defaults to `true`),
* `enableLiveFlagUpdates`: Enables live flag updates over SSE. Defaults to `true` in the React SDK.
* `apiBaseUrl`: Optional base URL for the Reflag API. This also controls the SSE origin used for live flag updates and automated feedback,
* `credentials`: Optional fetch credentials mode. Set to `"include"` when proxying through your backend and authenticating with cookies; this also enables credentials for live-update SSE connections.
* `appBaseUrl`: Optional base URL for the Reflag application. Use this to override the default app URL,
* `logger`: Optional custom logger implementation (`debug`, `info`, `warn`, `error`) used by the underlying client,
* `debug`: Set to `true` to enable debug logging to the console. If both `logger` and `debug` are provided, `logger` takes precedence,
* `toolbar`: Optional [configuration](https://docs.reflag.com/supported-languages/browser-sdk/globals.md#toolbaroptions) for the Reflag toolbar,
* `feedback`: Optional configuration for feedback collection

## `<ReflagBootstrappedProvider>` component <a href="#reflagbootstrappedprovider-component" id="reflagbootstrappedprovider-component"></a>

The `<ReflagBootstrappedProvider>` is a specialized version of the `ReflagProvider` that uses pre-fetched flag data for the initial render. This is ideal for server-side rendering scenarios.

The component accepts the following props:

* `flags`: Pre-fetched bootstrapped state of type `BootstrappedFlags` obtained from the Node SDK's `getFlagsForBootstrap()` method. This contains the context (`flags.context`), the evaluated flags (`flags.flags`), and an optional `flags.flagStateVersion`.
* All other props available in [`ReflagProvider`](#reflagprovider-component) are supported except `context`, `user`, `company`, and `other` (which are extracted from `flags.context`).

**Example:**

```tsx
import {
  ReflagBootstrappedProvider,
  BootstrappedFlags,
} from "@reflag/react-sdk";

interface AppProps {
  bootstrapData: BootstrappedFlags;
}

function App({ bootstrapData }: AppProps) {
  return (
    <ReflagBootstrappedProvider
      publishableKey="your-publishable-key"
      flags={bootstrapData}
      loadingComponent={<Loading />}
      debug={process.env.NODE_ENV === "development"}
    >
      <Router />
    </ReflagBootstrappedProvider>
  );
}
```

> \[!Note] When using `ReflagBootstrappedProvider`, pass the entire object returned by `getFlagsForBootstrap()` directly as the `flags` prop. The context is extracted from `flags.context`, and `flags.flagStateVersion` is used when present.
>
> With `ReflagBootstrappedProvider`, `useOptInFlags()` requests a flags refresh on first use. It returns `isLoading: true` (or suspends) until that refresh settles.
>
> Use `@reflag/node-sdk` v2 to produce the bootstrap data. It only includes flags marked as not secret (`secret: false`).
>
> After bootstrapping, any live flag updates are fetched directly by the browser SDK from Reflag using the browser-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the browser, later live refreshes may differ. In that case, keep `enableLiveFlagUpdates` disabled.
>
> Requesting opt-in flags also triggers a browser-side refresh, even when `enableLiveFlagUpdates` is disabled.

## Hooks <a href="#hooks" id="hooks"></a>

### `useFlag()` <a href="#useflag" id="useflag"></a>

Returns the value of a given flag for the current context. The hook provides type-safe access to flags and their values.

```tsx
import {
  useFlag,
  useIsLoading,
  useRequestFeedback,
  useTrack,
} from "@reflag/react-sdk";
import { Loading } from "./Loading";

function StartHuddleButton() {
  const isLoading = useIsLoading(); // true while flags are being loaded
  const isEnabled = useFlag("huddle"); // boolean indicating if the flag is enabled
  const settings = useFlag("huddle-settings", {
    question: "How do you like the Huddles feature?",
  }); // value of a multivariate flag, or the default
  const track = useTrack(); // function to track flag usage
  const requestFeedback = useRequestFeedback(); // function to request feedback

  if (isLoading) {
    return <Loading />;
  }

  if (!isEnabled) {
    return null;
  }

  return (
    <>
      <button onClick={() => track("huddle")}>Start huddle!</button>
      <button
        onClick={(e) =>
          requestFeedback({
            flagKey: "huddle",
            title: settings.question,
            position: {
              type: "POPOVER",
              anchor: e.currentTarget as HTMLElement,
            },
          })
        }
      >
        Give feedback!
      </button>
    </>
  );
}
```

Without a default, `useFlag(key)` returns a Boolean, using `false` while flags load or if the flag is missing. Pass a default to read a [multivariate flag](#multivariate-flags), such as `useFlag("model", "quick")`; the default sets the return type.

#### Suspense loading <a href="#suspense-loading" id="suspense-loading"></a>

`useFlag()` never suspends. Use `useFlagSuspense()` to suspend until flags are ready. It takes the same arguments as `useFlag()`, and the nearest `<Suspense>` boundary will render its fallback until flags are ready. If a flag is missing once they have loaded, it returns the default.

```tsx
import { Suspense } from "react";
import { ReflagProvider, useFlagSuspense } from "@reflag/react-sdk";

function Huddles() {
  const isEnabled = useFlagSuspense("huddle");
  return isEnabled ? <HuddleScreen /> : null;
}

<ReflagProvider publishableKey="..." context={context}>
  <Suspense fallback={<Loading />}>
    <Huddles />
  </Suspense>
</ReflagProvider>;
```

The provider's `suspense` prop doesn't affect `useFlag()` or `useFlagSuspense()`; it only applies to `useOptInFlags()`.

### `useOptInFlags()` <a href="#useoptinflags" id="useoptinflags"></a>

Use this hook to build an end-user opt-in UI for flags where opt-in is enabled in Reflag. It returns the opt-in flags, their loading state and a `setOptIn` function.

```tsx
import { type OptInFlag, useIsLoading, useOptInFlags } from "@reflag/react-sdk";

function OptInList() {
  const isProviderLoading = useIsLoading();
  const { flags, isLoading, setOptIn } = useOptInFlags();

  async function toggleOptIn(flag: OptInFlag) {
    try {
      const response = await setOptIn(flag.key, {
        optedIn: !flag.userOptedIn,
      });
      if (!response?.ok) {
        console.error("Could not update opt-in");
      }
    } catch (error) {
      console.error("Could not update opt-in", error);
    }
  }

  if (isProviderLoading || isLoading) {
    return <p>Loading…</p>;
  }

  return flags.map((flag) => (
    <button type="button" key={flag.key} onClick={() => toggleOptIn(flag)}>
      {flag.userOptedIn ? "Cancel opt-in" : `Try ${flag.name}`}
    </button>
  ));
}
```

Each entry includes the flag's `key`, `name`, `description`, a Boolean `value` that says whether the flag is on, and whether the user (`userOptedIn`) or company (`companyOptedIn`) has opted in.

By default, `setOptIn` changes the opt-in for the current user, so the current context must include a `user.id`. To manage the current company's opt-in instead, pass `scope: "company"`; the context must then include a `company.id`.

User and company opt-ins are managed independently. Setting `optedIn` to `false` removes the opt-in only for the selected scope. For example, cancelling a user's opt-in does not change the company's opt-in for the same flag.

`setOptIn` returns a promise so you can wait for the new membership state to be synchronized. On success, it resolves after the refreshed flag state has been applied locally, the requested membership change has been confirmed, and subscribers have been notified when flags change. React may not have committed the resulting render yet.

The promise resolves to a `Response`, or `undefined` if skipped due to invalid input, offline mode etc. Check `response?.ok` for success.

`useOptInFlags()` returns `{ flags, isLoading, setOptIn }`. The separate `useSetOptIn()` hook still works but is deprecated. With `ReflagBootstrappedProvider`, it fetches opt-in metadata on first use and reports `isLoading: true` until that refresh succeeds or fails.

If fetching opt-in metadata fails, loading ends without exposing an error. Call `client.refresh()` on the client returned by `useClient()` to retry.

With a regular `ReflagProvider`, opt-in metadata arrives as part of the normal initial flags request, so `useOptInFlags().isLoading` remains `false`. Use the general `useIsLoading()` hook or the provider's `loadingComponent` for that initial loading state.

`useOptInFlags()` also supports Suspense. It respects the provider-level `suspense` option, or you can enable it for only this hook with `useOptInFlags({ suspense: true })`. While required opt-in metadata is loading, the nearest `<Suspense>` boundary renders its fallback:

```tsx
import { Suspense } from "react";

<ReflagBootstrappedProvider publishableKey="..." flags={bootstrapData} suspense>
  <Suspense fallback={<Spinner />}>
    <OptInList />
  </Suspense>
</ReflagBootstrappedProvider>;
```

Opt-in metadata Suspense is primarily relevant with `ReflagBootstrappedProvider`. Use `useOptInFlags({ suspense: false })` to opt out for one call when Suspense is enabled on the provider.

### `useTrack()` <a href="#usetrack" id="usetrack"></a>

`useTrack()` lets you send custom events to Reflag. Use this whenever a user *uses* a feature. These events can be used to analyze feature usage in Reflag.

```tsx
import { useTrack } from "@reflag/react-sdk";

function StartHuddle() {
  const track = useTrack();
  return (
    <div>
      <button onClick={() => track("Huddle Started", { huddleType: "voice" })}>
        Start voice huddle!
      </button>
    </div>
  );
}
```

### `useRequestFeedback()` <a href="#userequestfeedback" id="userequestfeedback"></a>

`useRequestFeedback()` returns a function that lets you open up a dialog to ask for feedback on a specific feature. This is useful for collecting targeted feedback about specific features as part of roll out. See [Automated Feedback Surveys](https://docs.reflag.com/product-handbook/live-satisfaction) for how to do this automatically, without code.

When using the `useRequestFeedback` you must pass the flag key to `requestFeedback`. The example below shows how to use `position` to ensure the popover appears next to the "Give feedback!" button.

```tsx
import { useRequestFeedback } from "@reflag/react-sdk";

function FeedbackButton() {
  const requestFeedback = useRequestFeedback();
  return (
    <button
      onClick={(e) =>
        requestFeedback({
          flagKey: "huddle-flag",
          title: "How satisfied are you with file uploads?",
          position: {
            type: "POPOVER",
            anchor: e.currentTarget as HTMLElement,
          },
        })
      }
    >
      Give feedback!
    </button>
  );
}
```

See the [Feedback Documentation](https://github.com/reflagcom/javascript/blob/c9a90ea187026e2e22bdf5bd56df189b0fb12316/packages/browser-sdk/FEEDBACK.md#manual-feedback-collection) for more information on `requestFeedback` options.

### `useSendFeedback()` <a href="#usesendfeedback" id="usesendfeedback"></a>

Returns a function that lets you send feedback to Reflag. This is useful if you've manually collected feedback through your own UI and want to send it to Reflag.

```tsx
import type { FormEvent } from "react";
import { useSendFeedback } from "@reflag/react-sdk";

function CustomFeedbackForm() {
  const sendFeedback = useSendFeedback();

  const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    await sendFeedback({
      flagKey: "reflag-flag-key",
      score: parseInt(data.get("score") as string),
      comment: data.get("comment") as string,
    });
  };

  return <form onSubmit={handleSubmit}>...</form>;
}
```

### `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` <a href="#useupdateuser-useupdatecompany-and-useupdateothercontext" id="useupdateuser-useupdatecompany-and-useupdateothercontext"></a>

These hooks return functions that let you update the attributes for the currently set user, company, or other context. Updates to user/company are stored remotely and affect flag targeting, while "other" context updates only affect the current session.

```tsx
import {
  useUpdateUser,
  useUpdateCompany,
  useUpdateOtherContext,
} from "@reflag/react-sdk";

function FlagOptIn() {
  const updateUser = useUpdateUser();
  const updateCompany = useUpdateCompany();
  const updateOtherContext = useUpdateOtherContext();

  const handleUserUpdate = async () => {
    await updateUser({
      role: "admin",
      betaFlags: "enabled",
    });
  };

  const handleCompanyUpdate = async () => {
    await updateCompany({
      plan: "enterprise",
      employees: 500,
    });
  };

  const handleContextUpdate = async () => {
    await updateOtherContext({
      currentWorkspace: "workspace-123",
      theme: "dark",
    });
  };

  return (
    <div>
      <button onClick={handleUserUpdate}>Update User</button>
      <button onClick={handleCompanyUpdate}>Update Company</button>
      <button onClick={handleContextUpdate}>Update Context</button>
    </div>
  );
}
```

### `useClient()` <a href="#useclient" id="useclient"></a>

Returns the `ReflagClient` used by the `ReflagProvider`. The client offers more functionality that is not directly accessible thorough the other hooks.

```tsx
import { useClient } from "@reflag/react-sdk";

function LoggingWrapper({ children }: { children: ReactNode }) {
  const client = useClient();

  console.log(client.getContext());

  return children;
}
```

### `useIsLoading()` <a href="#useisloading" id="useisloading"></a>

Returns the loading state of the flags in the `ReflagClient`. Initially, the value will be `true` if no bootstrap flags have been provided and the client has not be initialized.

```tsx
import { useIsLoading } from "@reflag/react-sdk";
import { Spinner } from "./Spinner";

function LoadingWrapper({ children }: { children: ReactNode }) {
  const isLoading = useIsLoading();

  if (isLoading) {
    return <Spinner />;
  }

  return children;
}
```

### `useOnEvent()` <a href="#useonevent" id="useonevent"></a>

Attach a callback handler to client events to act on changes. It automatically disposes itself on unmount.

```tsx
import { useOnEvent } from "@reflag/react-sdk";

function LoggingWrapper({ children }: { children: ReactNode }) {
  useOnEvent("flagsUpdated", (newFlags) => {
    console.log(newFlags);
  });

  return children;
}
```

To listen to a client outside a provider, pass it as the third argument: `useOnEvent("flagsUpdated", handler, client)`.

## Migrating from v1 <a href="#migrating-from-v1" id="migrating-from-v1"></a>

* `useFlag()` returns the flag's value: replace `const { isEnabled } = useFlag(key)` with `const isEnabled = useFlag(key)`.
* Move remote config to a multivariate flag and read it with a default, such as `useFlag("model", "quick")`. Existing remote config isn't converted automatically.
* Use `useTrack()` and `useRequestFeedback()` instead of the flag's `track()` and `requestFeedback()`.
* Replace `useFlag(key, { suspense: true })` with `useFlagSuspense(key)`, and the flag's `isLoading` property with `useIsLoading()`. The provider's `suspense` prop now only applies to `useOptInFlags()`.
* `useFeature()` is removed. Use `useFlag()` instead.
* Use the `setOptIn` function returned by `useOptInFlags()`. `useSetOptIn()` still works but is deprecated.
* Opt-in entries have a Boolean `value` instead of `isEnabled`.
* Remove `fallbackFlags` and pass a default to each read instead, such as `useFlag("huddle", true)`.
* If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time, and mark the flags the browser needs as not secret.
* If you generate type declarations, regenerate them with the v2 CLI.

See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps.

## Migrating from Bucket SDK <a href="#migrating-from-bucket-sdk" id="migrating-from-bucket-sdk"></a>

If you have been using the Bucket SDKs, the following list will help you migrate to Reflag SDK:

* `Bucket*` classes, and types have been renamed to `Reflag*` (e.g. `BucketClient` is now `ReflagClient`)
* `Feature*` classes, and types have been renamed to `Flag*` (e.g. `Feature` is now `Flag`, `RawFeatures` is now `RawFlags`)
* When using strongly-typed flags, the new `Flags` interface replaced `Features` interface
* All methods that contained `feature` in the name have been renamed to use the `flag` terminology (e.g. `getFeature` is `getFlag`)
* The `fallbackFeatures` property has been removed; pass a default to each `useFlag()` read instead
* `featureKey` has been renamed to `flagKey` in all methods that accepts that argument
* The SDKs will not emit `evaluate` and `evaluate-config` events anymore
* The new cookies that are stored in the client's browser are now `reflag-*` prefixed instead of `bucket-*`
* The `featuresUpdated` hook has been renamed to `flagsUpdated`
* The `checkIsEnabled` and `checkConfig` hooks have been removed, use `check` from now on

To ease in transition to Reflag SDK, the `featuresUpdated` hook has been preserved as an alias for `flagsUpdated`. The `getFeature`, `getFeatures` and `useFeature` aliases have been removed; use `getFlag`, `getFlags` and `useFlag` instead.

If you are running with strict Content Security Policies active on your website, you will need change them as follows:

* `connect-src https://front.bucket.co` to `connect-src https://front.reflag.com`

## Content Security Policy (CSP) <a href="#content-security-policy-csp" id="content-security-policy-csp"></a>

See [CSP](https://github.com/reflagcom/javascript/blob/c9a90ea187026e2e22bdf5bd56df189b0fb12316/packages/browser-sdk/README.md#content-security-policy-csp) for info on using Reflag React SDK with CSP

## License <a href="#license" id="license"></a>

MIT License

Copyright (c) 2025 Bucket ApS


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.reflag.com/supported-languages/react-sdk.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
