Skip to content

React

The @edgeflags/react package wraps the core JavaScript SDK with a context provider and hooks that trigger re-renders when flag or config values change.

Installation

Terminal window
npm install @edgeflags/sdk @edgeflags/react

Provider setup

Wrap your app with EdgeFlagsProvider. You can either pass configuration props or an existing client instance:

import { EdgeFlagsProvider } from '@edgeflags/react';
function App() {
return (
<EdgeFlagsProvider
token="ff_production_abc123"
baseUrl="https://edgeflags.net"
context={{
user_id: currentUser.id,
plan: currentUser.plan,
custom: {},
}}
>
<YourApp />
</EdgeFlagsProvider>
);
}

Or with an external client (useful when you need access to the client outside React):

import { EdgeFlags } from '@edgeflags/sdk';
import { EdgeFlagsProvider } from '@edgeflags/react';
const client = new EdgeFlags({ token, baseUrl, context });
await client.init();
function App() {
return (
<EdgeFlagsProvider client={client}>
<YourApp />
</EdgeFlagsProvider>
);
}

useFlag

Read a flag value. The component re-renders when the value changes.

import { useFlag } from '@edgeflags/react';
function Checkout() {
const newCheckout = useFlag('new_checkout', false);
return newCheckout ? <NewCheckoutFlow /> : <LegacyCheckout />;
}

useConfig

Read a config value with the same re-render behavior.

import { useConfig } from '@edgeflags/react';
function PaymentForm() {
const config = useConfig<PaymentConfig>('payment_providers', {
stripe_enabled: true,
paypal_enabled: false,
});
return config.stripe_enabled ? <StripeForm /> : null;
}

useEdgeFlags

Access the underlying EdgeFlags client for manual operations like identify() or refresh().

import { useEdgeFlags } from '@edgeflags/react';
function LoginHandler() {
const ef = useEdgeFlags();
async function onLogin(user: User) {
await ef.identify({
user_id: user.id,
email: user.email,
plan: user.plan,
custom: {},
});
}
return <LoginForm onSuccess={onLogin} />;
}

Streaming

Pass streaming to the provider for real-time push updates instead of polling:

<EdgeFlagsProvider
token="ff_production_abc123"
baseUrl="https://edgeflags.net"
context={{ user_id: currentUser.id, custom: {} }}
streaming
>
<YourApp />
</EdgeFlagsProvider>

The useFlag and useConfig hooks re-render automatically on each streamed diff. See the Real-time Streaming guide for full WebSocket protocol details.

Testing

In tests, pass a mock client to the provider. Use createMockClient() from the core SDK:

import { createMockClient } from '@edgeflags/sdk';
import { EdgeFlagsProvider } from '@edgeflags/react';
const mock = createMockClient({ flags: { dark_mode: true } });
render(
<EdgeFlagsProvider client={mock}>
<ComponentUnderTest />
</EdgeFlagsProvider>
);

Cleanup

The provider handles cleanup automatically when it unmounts. If you passed an external client, you are responsible for calling destroy() yourself.