React

The Hyphen Toggle OpenFeature React Provider allows seamless feature flag evaluation using the OpenFeature standard within the Hyphen Toggle platform.

Native SDK @hyphen/react-sdk

The @hyphen/react-sdk is Hyphen's native React SDK that provides hooks and components for seamless feature flag integration in React applications. It offers a React-idiomatic interface without requiring OpenFeature.

Installation

Install the native React SDK:

npm install @hyphen/react-sdk

Setup and Initialization

Wrap your application with the HyphenProvider component:

import { HyphenProvider } from '@hyphen/react-sdk';

function App() {
  return (
    <HyphenProvider
      apiKey="your-client-key"
      application="your-application-name"
      environment="production"
    >
      <YourApp />
    </HyphenProvider>
  );
}

Usage

Basic Feature Flag Hook

Use the useFeatureFlag hook to check if a feature is enabled:

import { useFeatureFlag } from '@hyphen/react-sdk';

function MyComponent() {
  const isEnabled = useFeatureFlag('new-ui-design');

  return (
    <div>
      {isEnabled ? <NewUI /> : <LegacyUI />}
    </div>
  );
}

Feature Flag with User Context

Provide user context for targeted feature rollouts:

import { useFeatureFlag, useHyphenContext } from '@hyphen/react-sdk';

function Dashboard() {
  const { setContext } = useHyphenContext();

  // Set user context (typically in authentication flow)
  useEffect(() => {
    setContext({
      userId: user.id,
      email: user.email,
      customAttributes: {
        subscriptionTier: 'premium',
        role: 'admin'
      }
    });
  }, [user]);

  const showBetaFeatures = useFeatureFlag('beta-dashboard');

  return showBetaFeatures ? <BetaDashboard /> : <StandardDashboard />;
}

Getting Detailed Flag Information

Use useFeatureFlagDetails to get additional metadata:

import { useFeatureFlagDetails } from '@hyphen/react-sdk';

function FeatureComponent() {
  const { enabled, variant, metadata } = useFeatureFlagDetails('ab-test-feature');

  if (!enabled) return <DefaultView />;

  switch (variant) {
    case 'variant-a':
      return <VariantA metadata={metadata} />;
    case 'variant-b':
      return <VariantB metadata={metadata} />;
    default:
      return <DefaultView />;
  }
}

Conditional Rendering Component

Use the FeatureFlag component for declarative conditional rendering:

import { FeatureFlag } from '@hyphen/react-sdk';

function App() {
  return (
    <div>
      <FeatureFlag flag="new-header">
        <NewHeader />
      </FeatureFlag>

      <FeatureFlag flag="new-header" fallback={<OldHeader />}>
        <NewHeader />
      </FeatureFlag>

      {/* With variant support */}
      <FeatureFlag
        flag="pricing-page"
        variant="v2"
      >
        <PricingPageV2 />
      </FeatureFlag>
    </div>
  );
}

Loading States

Handle loading states while flags are being fetched:

import { useFeatureFlag, useHyphenClient } from '@hyphen/react-sdk';

function FeatureComponent() {
  const { isReady } = useHyphenClient();
  const isEnabled = useFeatureFlag('new-feature');

  if (!isReady) {
    return <LoadingSpinner />;
  }

  return isEnabled ? <NewFeature /> : <OldFeature />;
}

Real-time Flag Updates

Subscribe to flag changes in real-time:

import { useFeatureFlag, useFeatureFlagListener } from '@hyphen/react-sdk';

function DynamicFeature() {
  const isEnabled = useFeatureFlag('live-chat');

  useFeatureFlagListener('live-chat', (newValue) => {
    console.log('live-chat flag changed to:', newValue);
    // Optionally trigger side effects
  });

  return isEnabled ? <LiveChat /> : null;
}

HyphenProvider Configuration

The HyphenProvider accepts the following props:

PropTypeRequiredDescription
apiKeystringYesYour Hyphen client API key
applicationstringYesThe application id or alternate ID
environmentstringYesThe environment identifier (production, staging, etc.)
enableTelemetrybooleanNoEnable/disable usage telemetry (default: true)
autoUpdatebooleanNoEnable automatic flag updates (default: true)
updateIntervalnumberNoFlag update interval in seconds (default: 60)
defaultContextobjectNoDefault user context for all flag evaluations

Available Hooks

HookDescription
useFeatureFlagGet boolean value of a feature flag
useFeatureFlagDetailsGet detailed flag information including variants
useHyphenContextAccess and update user context
useHyphenClientAccess the underlying Hyphen client instance
useFeatureFlagListenerSubscribe to real-time flag changes

Open Feature

Installation

To use the Hyphen Toggle OpenFeature Web Provider for React, install the required packages:

npm install @openfeature/react-sdk @hyphen/openfeature-web-provider

Setup and Initialization

To begin using the Hyphen Provider, follow these steps:

  1. Import the required modules.

  2. Configure the provider with your publicKey, application name and environment.
    You can specify the environment in one of two formats:

    • Alternate ID (e.g., "production", "staging") — the environment in which your application is running.
    • Project Environment ID (e.g., pevr_abc123) — useful for internal references.
  3. Register the OpenFeature provider.

import { OpenFeature, OpenFeatureProvider } from '@openfeature/react-sdk';
import { HyphenProvider, HyphenProviderOptions } from '@hyphen/openfeature-web-provider';

const publicKey = 'your-public-key'; // Replace with your Hyphen publicKey

const options: HyphenProviderOptions = {
  application: 'your-app-name',
  environment: 'production', // or project environment ID
};

await OpenFeature.setProviderAndWait(new HyphenProvider(publicKey, options));

function App() {
  return (
    <OpenFeatureProvider>
      <Page/>
    </OpenFeatureProvider>
  );
}
  1. Use OpenFeature.setContext to configure the context needed for feature targeting. This context should include relevant user information, typically obtained from an authentication process.
const AuthContext = createContext({ isLoading: true, user: null });

export const MockAuthProvider = ({ children }: { children: React.ReactNode }) => {
   const [authState, setAuthState] = useState({ isLoading: true, user: null });

   useEffect(() => {
     setTimeout(() => {
       const user = {
         id: 'user-123',
         name: 'John Doe',
         email: '[email protected]',
       };
       OpenFeature.setContext({
         targetingKey: user.id,
         user,
         customAttributes: { role: user.role }, // Additional targeting attributes
       });

      setAuthState({ isLoading: false, user });
       }, 1000);
   }, []);

   return <AuthContext.Provider value={authState}>{children}</AuthContext.Provider>;
   };

   export const useAuth = () => useContext(AuthContext);

Usage

Evaluation Context Example

Use any of the OpenFeature evaluation hooks to evaluate flags.

import { useFlag } from '@openfeature/react-sdk';

function Page() {
const { value: isFeatureEnabled } = useFlag('your-flag-key', false);
  return (
    <div>
      <header>
        {isFeatureEnabled ? <p>Welcome to this OpenFeature-enabled React app!</p> : <p>Welcome to this React app.</p>}
      </header>
    </div>
  )
}

Configuration

Options

OptionTypeRequiredDescription
applicationstringYesThe application id or alternate ID.
environmentstringYesThe environment identifier for the Hyphen project (project environment ID or alternateId).
horizonUrlsstring[]NoHyphen Horizon URLs for fetching flags.
enableToggleUsagebooleanNoEnable/disable telemetry (default: true).

Context

Provide an EvaluationContext to pass contextual data for feature evaluation.

FieldTypeRequiredDescription
targetingKeystringYesThe key used for caching the evaluation response.
ipAddressstringNoThe IP address of the user making the request.
customAttributesRecord<string, any>NoCustom attributes for additional contextual information.
userobjectNoAn object containing user-specific information for the evaluation.
user.idstringNoThe unique identifier of the user.
user.emailstringNoThe email address of the user.
user.namestringNoThe name of the user.
user.customAttributesRecord<string, any>NoCustom attributes specific to the user.