Using ConfigCat's OpenFeature Provider in React
Getting started
OpenFeature offers a React SDK to streamline the use of OpenFeature in React applications. This SDK is built on top of the OpenFeature JavaScript Web SDK.
Since ConfigCat implements a provider for the Web SDK, you can use ConfigCat with the OpenFeature React SDK, as explained below.
1. Install the React SDK and the ConfigCat provider
npm i @openfeature/react-sdk @openfeature/config-cat-web-provider
2. Initialize the React SDK
The ConfigCatWebProvider.create()
function takes the SDK key and an optional options
argument containing additional
configuration options for the underlying ConfigCat client:
import { OpenFeature, OpenFeatureProvider } from '@openfeature/react-sdk';
import { ConfigCatWebProvider } from '@openfeature/config-cat-web-provider';
import { createConsoleLogger, LogLevel } from 'configcat-js-ssr';
const configCatProvider = ConfigCatWebProvider.create('#YOUR-SDK-KEY#', {
// Specify options for the underlying ConfigCat client
logger: createConsoleLogger(LogLevel.Info),
setupHooks: (hooks) => hooks.on('clientReady', () => console.log('Client is ready!')),
// ...
});
// Set the initial context for your evaluations
OpenFeature.setContext({
targetingKey: 'user-1',
admin: false
});
// Instantiate and set our provider (be sure this only happens once)!
// Note: there's no need to await its initialization, the React SDK handles re-rendering and suspense for you!
OpenFeature.setProvider(configCatProvider);
// Enclose your content in the configured provider
function App() {
return (
<OpenFeatureProvider>
<Page />
</OpenFeatureProvider>
);
}
The OpenFeatureProvider
is a React context provider which
represents a scope for feature flag evaluations within a React application. It binds an OpenFeature client to all
evaluations within child components, and allows the use of evaluation hooks.
3. Use your feature flag
import { useFlag } from '@openfeature/react-sdk';
function Page() {
// Use the "query-style" flag evaluation hook, specifying a flag-key and a default value.
const { value: isAwesomeFeatureEnabled } = useFlag('isAwesomeFeatureEnabled', false);
return (
<div>
{isAwesomeFeatureEnabled ? <p>Awesome feature is enabled!</p> : <p>Awesome feature is not enabled.</p>}
</div>
)
}
Evaluation Context
An evaluation context in the OpenFeature specification is a container for arbitrary contextual data that can be used as a basis for feature flag evaluation.
You can find here how the ConfigCat provider translates these evaluation contexts to ConfigCat User Objects.
Advanced features
Read the documentation of the OpenFeature React SDK to learn more about the advanced capabilities of the SDK.