What is @unleash/proxy-client-react?
@unleash/proxy-client-react is a React client for the Unleash feature management system. It allows developers to easily integrate feature toggles into their React applications, enabling dynamic feature management and experimentation.
What are @unleash/proxy-client-react's main functionalities?
Initialize Unleash Client
This code initializes the Unleash client with the necessary configuration, including the URL of the Unleash API, the client key, and the application name. The `start` method is called to begin fetching feature toggles.
import { UnleashClient } from '@unleash/proxy-client-react';
const client = new UnleashClient({
url: 'https://app.unleash-hosted.com/demo/api/',
clientKey: 'proxy-client-key',
appName: 'my-react-app'
});
client.start();
Use Feature Toggles in Components
This code demonstrates how to use the `useFlag` hook to check the status of a feature toggle within a React component. Depending on whether the feature toggle is enabled or disabled, different content is rendered.
import { useFlag } from '@unleash/proxy-client-react';
const MyComponent = () => {
const isEnabled = useFlag('my-feature-toggle');
return (
<div>
{isEnabled ? <p>Feature is enabled</p> : <p>Feature is disabled</p>}
</div>
);
};
Custom Context Provider
This code shows how to wrap your application with the `UnleashProvider` to provide the Unleash client configuration context to all components within the application. This makes it easier to use feature toggles throughout the app.
import { UnleashProvider } from '@unleash/proxy-client-react';
const App = () => (
<UnleashProvider
config={{
url: 'https://app.unleash-hosted.com/demo/api/',
clientKey: 'proxy-client-key',
appName: 'my-react-app'
}}
>
<MyComponent />
</UnleashProvider>
);
Other packages similar to @unleash/proxy-client-react
react-feature-toggles
react-feature-toggles is a lightweight library for managing feature toggles in React applications. It provides a simple API for defining and using feature toggles, but it does not offer the same level of integration with a feature management system like Unleash.
launchdarkly-react-client-sdk
launchdarkly-react-client-sdk is the official React SDK for LaunchDarkly, a feature management platform. It offers similar functionality to @unleash/proxy-client-react, including feature flag evaluation and context management, but it is tied to the LaunchDarkly service.
react-ab-test
react-ab-test is a library for A/B testing in React applications. It allows developers to define experiments and variants, and track user interactions. While it focuses on A/B testing rather than feature toggles, it provides similar capabilities for experimentation.
DISCLAIMER:
This library is meant to be used with the unleash-proxy. The proxy application layer will sit between your unleash instance and your client applications, and provides performance and security benefits. DO NOT TRY to connect this library directly to the unleash instance, as the datasets follow different formats because the proxy only returns evaluated toggle information.
Installation
npm install @unleash/proxy-client-react
// or
yarn add @unleash/proxy-client-react
Upgrade path from v1 -> v2
If you were previously using the built in Async storage used in the unleash-proxy-client-js, this no longer comes bundled with the library. You will need to install the storage adapter for your preferred storage solution. Otherwise there are no breaking changes.
Initialization
Import the provider like this in your entrypoint file (typically index.js/ts):
import FlagProvider from '@unleash/proxy-client-react';
const config = {
url: 'https://HOSTNAME/proxy',
clientKey: 'PROXYKEY',
refreshInterval: 15,
appName: 'your-app-name',
environment: 'dev',
};
ReactDOM.render(
<React.StrictMode>
<FlagProvider config={config}>
<App />
</FlagProvider>
</React.StrictMode>,
document.getElementById('root')
);
Alternatively, you can pass your own client in to the FlagProvider:
import FlagProvider, { UnleashClient } from '@unleash/proxy-client-react';
const config = {
url: 'https://HOSTNAME/proxy',
clientKey: 'PROXYKEY',
refreshInterval: 15,
appName: 'your-app-name',
environment: 'dev',
};
const client = new UnleashClient(config);
ReactDOM.render(
<React.StrictMode>
<FlagProvider unleashClient={client}>
<App />
</FlagProvider>
</React.StrictMode>,
document.getElementById('root')
);
Deferring client start
By default, the Unleash client will start polling the Proxy for toggles immediately when the FlagProvider
component renders. You can delay the polling by:
- setting the
startClient
prop to false
- passing a client instance to the
FlagProvider
ReactDOM.render(
<React.StrictMode>
<FlagProvider unleashClient={client} startClient={false}>
<App />
</FlagProvider>
</React.StrictMode>,
document.getElementById('root')
);
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.
const client = new UnleashClient({ })
useEffect(() => {
const asyncProcess = async () => {
client.start()
}
asyncProcess()
}, [])
return (
<FlagProvider unleashClient={client} startClient={false}>
<App />
</FlagProvider>
)
Usage
Check feature toggle status
To check if a feature is enabled:
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:
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.
import { useFlagsStatus } from '@unleash/proxy-client-react'
const MyApp = () => {
const { flagsReady, flagsError } = useFlagsStatus();
if (!flagsReady) {
return <Loading />
}
return <MyComponent error={flagsError}/>
}
Updating context
Follow the following steps in order to update the unleash context:
import { useUnleashContext, useFlag } from '@unleash/proxy-client-react'
const MyComponent = ({ userId }) => {
const variant = useFlag("my-toggle");
const updateContext = useUnleashContext();
useEffect(() => {
updateContext({ userId })
}, [userId])
useEffect(() => {
async function run() {
await updateContext({ userId });
console.log('new flags loaded for', userId);
}
run();
}, [userId]);
}
React Native
Because React Native doesn't run in a web browser, it doesn't have access to the localStorage
API. Instead, you need to tell Unleash to use your specific storage provider. The most common storage provider for React Native is AsyncStorage.
To configure it, add the following property to your configuration object:
const config = {
storageProvider: {
save: (name, data) => AsyncStorage.setItem(name, JSON.stringify(data)),
get: async (name) => {
const data = await AsyncStorage.getItem(name);
return data ? JSON.parse(data) : undefined;
}
},
};