React SDK usage
This page describes how to use the OpenFeature React SDK for your client application.
About this provider
OpenFeature React SDK allows you to connect to your GO Feature Flag instance with the @openfeature/react-sdk
.
If you work with React the @openfeature/react-sdk
will give you a better integration with your React application.
To integrate it with GO Feature Flag, you need to use the @openfeature/go-feature-flag-web-provider
provider.
Install the provider
npm install @openfeature/go-feature-flag-web-provider
npm install @openfeature/web-sdk
npm install @openfeature/react-sdk
npm install @openfeature/core
How to use the provider?
OpenFeatureProvider context provider
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.
import { EvaluationContext, OpenFeature, OpenFeatureProvider, useFlag } from "@openfeature/react-sdk";
import { GoFeatureFlagWebProvider } from "@openfeature/go-feature-flag-web-provider";
const goFeatureFlagWebProvider = new GoFeatureFlagWebProvider({
endpoint: "http://localhost:1031"
});
// 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(goFeatureFlagWebProvider);
// Enclose your content in the configured provider
function App() {
return (
<OpenFeatureProvider>
<Page />
</OpenFeatureProvider>
);
}