React SDK

View as Markdown

The Unleash React SDK lets you evaluate feature flags in React applications. It connects to Unleash or Unleash Edge to fetch evaluated flags for a given Unleash context.

You can use this SDK with Unleash Enterprise or Unleash Open Source.

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.

Installation

$npm install @unleash/proxy-client-react unleash-proxy-client

Example application

To see the SDK in action, explore the examples/basic-app 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 client as a base.

Initialization

You can use the Frontend API or unleash-edge.

For the following step you will need a frontend API Token or unleash-edge pretrusted token.

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

1import { createRoot } from 'react-dom/client';
2import { FlagProvider } from '@unleash/proxy-client-react';
3
4const config = {
5 url: '<unleash-url>/api/frontend', // Your Frontend API URL or the Unleash Edge URL
6 clientKey: '<your-token>', // A frontend token OR one of your unleash-edge pretrusted token
7 refreshInterval: 15, // How often (in seconds) the client should poll the proxy for updates
8 appName: 'your-app-name', // The name of your application. It's only used for identifying your application
9};
10
11const root = createRoot(document.getElementById('root'));
12
13root.render(
14 <React.StrictMode>
15 <FlagProvider config={config}>
16 <App />
17 </FlagProvider>
18 </React.StrictMode>
19);

Testing feature flags locally? The 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 instance. Set clientKey to a frontend API token.

To connect this SDK to unleash-edge, follow the documentation provided in the unleash-edge repository.

Check flags

To check if a feature is enabled:

1import { useFlag } from '@unleash/proxy-client-react';
2
3const TestComponent = () => {
4 const enabled = useFlag('travel.landing');
5
6 if (enabled) {
7 return <SomeComponent />;
8 }
9 return <AnotherComponent />;
10};
11
12export default TestComponent;

Check variants

To check variants:

1import { useVariant } from '@unleash/proxy-client-react';
2
3const TestComponent = () => {
4 const variant = useVariant('travel.landing');
5
6 if (variant.enabled && variant.name === 'SomeComponent') {
7 return <SomeComponent />;
8 } else if (variant.enabled && variant.name === 'AnotherComponent') {
9 return <AnotherComponent />;
10 }
11 return <DefaultComponent />;
12};
13
14export 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.

1import { useFlagsStatus } from '@unleash/proxy-client-react';
2
3const MyApp = () => {
4 const { flagsReady, flagsError } = useFlagsStatus();
5
6 if (!flagsReady) {
7 return <Loading />;
8 }
9 return <MyComponent error={flagsError} />;
10};

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:

1import { useUnleashContext, useFlag } from '@unleash/proxy-client-react';
2
3const MyComponent = ({ userId }) => {
4 const variant = useFlag('my-toggle');
5 const updateContext = useUnleashContext();
6
7 useEffect(() => {
8 // context is updated with userId
9 updateContext({ userId });
10 }, [userId]);
11
12 // OR if you need to perform an action right after new context is applied
13 useEffect(() => {
14 async function run() {
15 // Can wait for the new flags to pull in from the different context
16 await updateContext({ userId });
17 console.log('new flags loaded for', userId);
18 }
19 run();
20 }, [userId]);
21};

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.

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

1import { useUnleashClient, useFlag } from '@unleash/proxy-client-react';
2
3const MyComponent = ({ userId }) => {
4 const client = useUnleashClient();
5
6 useEffect(() => {
7 if (client) {
8 const handleError = () => {
9 // Handle error
10 }
11
12 client.on('error', handleError)
13 }
14
15 return () => {
16 client.off('error', handleError)
17 }
18 }, [client])
19
20 // ...rest of component
21};

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.

1const client = new UnleashClient({
2 /* ... */
3});
4
5const MyAppComponent = () => {
6 useEffect(() => {
7 const asyncProcess = async () => {
8 // do async work ...
9 client.start();
10 };
11 asyncProcess();
12 }, []);
13
14 return (
15 // Pass client as `unleashClient` and set `startClient` to `false`
16 <FlagProvider unleashClient={client} startClient={false}>
17 <App />
18 </FlagProvider>
19 );
20};

Use Unleash client directly

1import { useUnleashContext, useUnleashClient } from '@unleash/proxy-client-react'
2
3const MyComponent = ({ userId }) => {
4 const client = useUnleashClient();
5
6 const login = () => {
7 // login user
8 if (client.isEnabled("new-onboarding")) {
9 // Send user to new onboarding flow
10 } else {
11 // send user to old onboarding flow
12 }
13 }
14
15 return <LoginForm login={login}/>
16}

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:

1import React from 'react';
2import {
3 useFlag,
4 useUnleashClient,
5 useUnleashContext,
6 useVariant,
7 useFlagsStatus,
8} from '@unleash/proxy-client-react';
9
10interface IUnleashClassFlagProvider {
11 render: (props: any) => React.ReactNode;
12 flagName: string;
13}
14
15export const UnleashClassFlagProvider = ({
16 render,
17 flagName,
18}: IUnleashClassFlagProvider) => {
19 const enabled = useFlag(flagName);
20 const variant = useVariant(flagName);
21 const client = useUnleashClient();
22
23 const updateContext = useUnleashContext();
24 const { flagsReady, flagsError } = useFlagsStatus();
25
26 const isEnabled = () => {
27 return enabled;
28 };
29
30 const getVariant = () => {
31 return variant;
32 };
33
34 const getClient = () => {
35 return client;
36 };
37
38 const getUnleashContextSetter = () => {
39 return updateContext;
40 };
41
42 const getFlagsStatus = () => {
43 return { flagsReady, flagsError };
44 };
45
46 return (
47 <>
48 {render({
49 isEnabled,
50 getVariant,
51 getClient,
52 getUnleashContextSetter,
53 getFlagsStatus,
54 })}
55 </>
56 );
57};

Wrap your components like so:

1<UnleashClassFlagProvider
2 flagName="demoApp.step1"
3 render={({ isEnabled, getClient }) => (
4 <MyClassComponent isEnabled={isEnabled} getClient={getClient} />
5 )}
6/>

Developer toolbar

The Developer 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

$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:

1import { useFlag, useVariant } from '@unleash/proxy-client-react';
2import { UnleashToolbarProvider } from '@unleash/toolbar/react';
3import '@unleash/toolbar/toolbar.css';
4
5const config = {
6 url: 'https://your-unleash.com/api/frontend',
7 clientKey: 'your-frontend-token',
8 appName: 'my-app',
9 refreshInterval: 15
10};
11
12function App() {
13 return (
14 <UnleashToolbarProvider
15 config={config}
16 toolbarOptions={{
17 storageMode: 'local',
18 position: 'bottom-right',
19 themePreset: 'dark'
20 }}
21 >
22 <MyComponent />
23 </UnleashToolbarProvider>
24 );
25}
26
27function MyComponent() {
28 // Hooks from the official SDK work seamlessly with toolbar overrides
29 const isEnabled = useFlag('my-feature');
30 const variant = useVariant('my-experiment');
31
32 return (
33 <div>
34 {isEnabled && <NewFeature />}
35 {variant.name === 'variant-a' && <VariantA />}
36 </div>
37 );
38}

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:

1import { FlagProvider } from '@unleash/proxy-client-react';
2import { UnleashToolbarProvider } from '@unleash/toolbar/react';
3import '@unleash/toolbar/toolbar.css';
4
5const Provider = import.meta.env.DEV
6 ? UnleashToolbarProvider
7 : FlagProvider;
8
9function App() {
10 return (
11 <Provider config={config}>
12 <MyComponent />
13 </Provider>
14 );
15}

Refer to the Developer Toolbar documentation for configuration options, API reference, and the complete React example on GitHub.

React Native

For React Native and Expo applications, use the dedicated React Native SDK. It wraps this SDK and handles AsyncStorage and startTransition configuration automatically.

Migrating to v5

From v4

FlagContext public interface changed. 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.