> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.getunleash.io/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.getunleash.io/_mcp/server.

# React SDK

> Set up the Unleash React SDK to evaluate feature flags with hooks, variants, context updates, events, and toolbar support.

The Unleash React SDK lets you evaluate feature flags in React applications. It connects to Unleash or [Unleash Edge](/unleash-edge) to fetch evaluated flags for a given [Unleash context](/concepts/unleash-context).

You can use this SDK with [Unleash Enterprise](https://www.getunleash.io/pricing) or [Unleash Open Source](https://github.com/Unleash/unleash).

For an overview of how Unleash SDKs work, including offline behavior, feature compatibility across SDKs, and default refresh and metrics intervals, refer to the [SDK overview](/sdks).

## Installation

```bash
npm install @unleash/proxy-client-react unleash-proxy-client
```

```bash
yarn add @unleash/proxy-client-react unleash-proxy-client
```

## Example application

To see the SDK in action, explore the [`examples/basic-app`](https://github.com/Unleash/proxy-client-react/blob/main/examples/basic-app/README.md) directory.
It contains a minimal Vite + React setup that connects to Unleash, evaluates a feature toggle,
and updates the evaluation context dynamically at runtime. The README in that folder includes step-by-step instructions
for running the example.

This library uses the core [unleash-js-sdk](https://github.com/Unleash/unleash-js-sdk) client as a base.

## Initialization

You can use the [Frontend API](/api#frontend-api) or [unleash-edge](/unleash-edge).

For the following step you will need a [frontend API Token](/api#frontend-api) or [unleash-edge pretrusted token](/unleash-edge#pretrusted-tokens).

Import the provider like this in your entrypoint file (typically index.js/ts):

```jsx
import { createRoot } from 'react-dom/client';
import { FlagProvider } from '@unleash/proxy-client-react';

const config = {
  url: '<unleash-url>/api/frontend', // Your Frontend API URL or the Unleash Edge URL
  clientKey: '<your-token>', // A frontend token OR one of your unleash-edge pretrusted token
  refreshInterval: 15, // How often (in seconds) the client should poll the proxy for updates
  appName: 'your-app-name', // The name of your application. It's only used for identifying your application
};

const root = createRoot(document.getElementById('root'));

root.render(
  <React.StrictMode>
    <FlagProvider config={config}>
      <App />
    </FlagProvider>
  </React.StrictMode>
);
```

**Testing feature flags locally?** The [Developer Toolbar](#developer-toolbar) provides a drop-in replacement for `FlagProvider` that lets you override flag values and context at runtime. Use `UnleashToolbarProvider` from `@unleash/toolbar/react` during development.

### Connection options

Set `url` to the `/api/frontend` endpoint of your Unleash instance or your [Unleash Edge](/unleash-edge) instance. Set `clientKey` to a [frontend API token](/concepts/api-tokens-and-client-keys#frontend-tokens).

To connect this SDK to unleash-edge, follow the documentation provided in the [unleash-edge repository](https://github.com/unleash/unleash-edge).

## Check flags

To check if a feature is enabled:

```jsx
import { useFlag } from '@unleash/proxy-client-react';

const TestComponent = () => {
  const enabled = useFlag('travel.landing');

  if (enabled) {
    return <SomeComponent />;
  }
  return <AnotherComponent />;
};

export default TestComponent;
```

## Check variants

To check variants:

```jsx
import { useVariant } from '@unleash/proxy-client-react';

const TestComponent = () => {
  const variant = useVariant('travel.landing');

  if (variant.enabled && variant.name === 'SomeComponent') {
    return <SomeComponent />;
  } else if (variant.enabled && variant.name === 'AnotherComponent') {
    return <AnotherComponent />;
  }
  return <DefaultComponent />;
};

export default TestComponent;
```

### Defer rendering until flags fetched

useFlagsStatus retrieves the ready state and error events.
Follow the following steps in order to delay rendering until the flags have been fetched.

```jsx
import { useFlagsStatus } from '@unleash/proxy-client-react';

const MyApp = () => {
  const { flagsReady, flagsError } = useFlagsStatus();

  if (!flagsReady) {
    return <Loading />;
  }
  return <MyComponent error={flagsError} />;
};
```

### Unleash context

Initial context can be specified on a `FlagProvider` `config.context` property.

`<FlagProvider config={{ ...config, context: { userId: 123 }}>`

This code sample shows you how to update the unleash context dynamically:

```jsx
import { useUnleashContext, useFlag } from '@unleash/proxy-client-react';

const MyComponent = ({ userId }) => {
  const variant = useFlag('my-toggle');
  const updateContext = useUnleashContext();

  useEffect(() => {
    // context is updated with userId
    updateContext({ userId });
  }, [userId]);

  // OR if you need to perform an action right after new context is applied
  useEffect(() => {
    async function run() {
      // Can wait for the new flags to pull in from the different context
      await updateContext({ userId });
      console.log('new flags loaded for', userId);
    }
    run();
  }, [userId]);
};
```

### Events

The core JavaScript client emits various types of events depending on internal activities. You can listen to these events by using a hook to access the client and then directly attaching event listeners. Alternatively, if you're using the FlagProvider with a client, you can directly use this client to listen to the events. [See the full list of events here.](https://github.com/Unleash/unleash-proxy-client-js?tab=readme-ov-file#available-events)

NOTE: `FlagProvider` uses these internal events to provide information through `useFlagsStatus`.

```jsx
import { useUnleashClient, useFlag } from '@unleash/proxy-client-react';

const MyComponent = ({ userId }) => {
  const client = useUnleashClient();

  useEffect(() => {
    if (client) {
      const handleError = () => {
        // Handle error
      }

      client.on('error', handleError)
    }

    return () => {
      client.off('error', handleError)
    }
  }, [client])

  // ...rest of component
};
```

## Deferring client start

By default, the Unleash client will start polling the Proxy for toggles immediately when the `FlagProvider` component renders. You can prevent it by setting `startClient` prop to `false`. This is useful when you'd like to for example bootstrap the client and work offline.

Deferring the client start gives you more fine-grained control over when to start fetching the feature toggle configuration. This could be handy in cases where you need to get some other context data from the server before fetching toggles, for instance.

To start the client, use the client's `start` method. The below snippet of pseudocode will defer polling until the end of the `asyncProcess` function.

```jsx
const client = new UnleashClient({
  /* ... */
});

const MyAppComponent = () => {
  useEffect(() => {
    const asyncProcess = async () => {
      // do async work ...
      client.start();
    };
    asyncProcess();
  }, []);

  return (
    // Pass client as `unleashClient` and set `startClient` to `false`
    <FlagProvider unleashClient={client} startClient={false}>
      <App />
    </FlagProvider>
  );
};
```

## Use Unleash client directly

```jsx
import { useUnleashContext, useUnleashClient } from '@unleash/proxy-client-react'

const MyComponent = ({ userId }) => {
  const client = useUnleashClient();

  const login = () => {
    // login user
    if (client.isEnabled("new-onboarding")) {
      // Send user to new onboarding flow
    } else {
      // send user to old onboarding flow
    }
  }

  return <LoginForm login={login}/>
}
```

## Usage with class components

Since this library uses hooks you have to implement a wrapper to use with class components. Beneath you can find an example of how to use this library with class components, using a custom wrapper:

```jsx
import React from 'react';
import {
  useFlag,
  useUnleashClient,
  useUnleashContext,
  useVariant,
  useFlagsStatus,
} from '@unleash/proxy-client-react';

interface IUnleashClassFlagProvider {
  render: (props: any) => React.ReactNode;
  flagName: string;
}

export const UnleashClassFlagProvider = ({
  render,
  flagName,
}: IUnleashClassFlagProvider) => {
  const enabled = useFlag(flagName);
  const variant = useVariant(flagName);
  const client = useUnleashClient();

  const updateContext = useUnleashContext();
  const { flagsReady, flagsError } = useFlagsStatus();

  const isEnabled = () => {
    return enabled;
  };

  const getVariant = () => {
    return variant;
  };

  const getClient = () => {
    return client;
  };

  const getUnleashContextSetter = () => {
    return updateContext;
  };

  const getFlagsStatus = () => {
    return { flagsReady, flagsError };
  };

  return (
    <>
      {render({
        isEnabled,
        getVariant,
        getClient,
        getUnleashContextSetter,
        getFlagsStatus,
      })}
    </>
  );
};
```

Wrap your components like so:

```jsx
<UnleashClassFlagProvider
  flagName="demoApp.step1"
  render={({ isEnabled, getClient }) => (
    <MyClassComponent isEnabled={isEnabled} getClient={getClient} />
  )}
/>
```

## Developer toolbar

The [Developer Toolbar](/integrate/toolbar) provides runtime flag and context overrides during development. It wraps the standard React SDK with override capabilities while maintaining the same hook API.

### Installation

```bash
npm install @unleash/toolbar @unleash/proxy-client-react unleash-proxy-client
```

### Usage

Replace `FlagProvider` with `UnleashToolbarProvider` from `@unleash/toolbar/react`. The provider accepts the same `config` prop, plus optional `toolbarOptions`:

```tsx {14-21}
import { useFlag, useVariant } from '@unleash/proxy-client-react';
import { UnleashToolbarProvider } from '@unleash/toolbar/react';
import '@unleash/toolbar/toolbar.css';

const config = {
  url: 'https://your-unleash.com/api/frontend',
  clientKey: 'your-frontend-token',
  appName: 'my-app',
  refreshInterval: 15
};

function App() {
  return (
    <UnleashToolbarProvider
      config={config}
      toolbarOptions={{
        storageMode: 'local',
        position: 'bottom-right',
        themePreset: 'dark'
      }}
    >
      <MyComponent />
    </UnleashToolbarProvider>
  );
}

function MyComponent() {
  // Hooks from the official SDK work seamlessly with toolbar overrides
  const isEnabled = useFlag('my-feature');
  const variant = useVariant('my-experiment');

  return (
    <div>
      {isEnabled && <NewFeature />}
      {variant.name === 'variant-a' && <VariantA />}
    </div>
  );
}
```

Key points:

* Import hooks from `@unleash/proxy-client-react` (the official SDK)
* The toolbar automatically handles `FlagProvider` internally
* All hooks re-render automatically when you change overrides in the toolbar UI

### Conditional initialization

Enable the toolbar only in development to avoid shipping it to production:

```tsx {5-7}
import { FlagProvider } from '@unleash/proxy-client-react';
import { UnleashToolbarProvider } from '@unleash/toolbar/react';
import '@unleash/toolbar/toolbar.css';

const Provider = import.meta.env.DEV
  ? UnleashToolbarProvider
  : FlagProvider;

function App() {
  return (
    <Provider config={config}>
      <MyComponent />
    </Provider>
  );
}
```

Refer to the [Developer Toolbar documentation](/integrate/toolbar) for configuration options, API reference, and the [complete React example on GitHub](https://github.com/Unleash/toolbar/tree/main/examples/react).

## React Native

For React Native and Expo applications, use the dedicated [React Native SDK](/sdks/react-native). It wraps this SDK and handles `AsyncStorage` and `startTransition` configuration automatically.

## Migrating to v5

### From v4

[FlagContext public interface changed](https://github.com/Unleash/unleash-react-sdk/commit/b783ef4016dbb881ac3d878cffaf5241b047cc35#diff-825c82ad66c3934257e0ee3e0511d9223db22e7ddf5de9cbdf6485206e3e02cfL20-R20). If you used FlagContext directly you may have to adjust your code slightly to accommodate the new type changes.

### From v3

The `startClient` option has been simplified. It now also works if you don't pass a custom client with it. It defaults to `true`. The v4 major bump was driven by Node 14 end of life — no other breaking changes.

### From v2

The unleash client is now a peer dependency instead of a bundled dependency. Two distribution builds are provided: one for the server (`dist/index.js`) and one for the browser (`dist/index.browser.js`). If you can't resolve the peer dependency, run `npm install unleash-proxy-client`.

### From v1

The built-in async storage is no longer bundled. Install a storage adapter for your preferred storage solution. No other breaking changes.