React hooks for feature flag evaluation in components
Last updated November 14, 2026
React Hooks
@flaggr/sdk/react provides a provider and hooks for evaluating feature flags in React components. It's part of the @flaggr/sdk package; React 18 or later is a peer dependency.
npm install @flaggr/sdkSetup
Wrap your app with FlaggrProvider:
import { FlaggrProvider } from '@flaggr/sdk/react'
function App() {
return (
<FlaggrProvider apiKey="fgr_your_token" serviceId="web-app" environment="production">
<YourApp />
</FlaggrProvider>
)
}| Prop | Description |
|---|---|
serviceId | The service whose flags the hooks evaluate |
apiKey | A project API token. In a browser bundle, use an evaluation-only or read-only token |
environment | The environment to evaluate in. Set it: without one, the data plane (https://api.flaggr.dev, the default) evaluates in production, and the control plane on https://flaggr.dev in development |
config | Any createFlaggr option, such as updateMode, context, defaults or exposeFlags |
When you pass serviceId, the apiKey, serviceId and environment props override the same fields in config. Without serviceId the provider uses config as it is, and without either it reads FLAGGR_SERVICE_ID, FLAGGR_API_KEY, FLAGGR_ENVIRONMENT and FLAGGR_API_URL (or their NEXT_PUBLIC_ versions) from process.env. From 0.5.0 the SDK reads each NEXT_PUBLIC_FLAGGR_* variable by its literal name, so Next.js inlines the values set at build time into browser bundles. 0.4.0 looks them up at run time and finds none there, so with 0.4.0 pass them as props, as in the next section.
The provider creates one client when it first renders and destroys it when it unmounts. Changing its props later doesn't create a new client: to evaluate for a different user, call setContext on the client from useFlaggr().
Under React Strict Mode in development (on by default in the Next.js App Router), React unmounts and remounts the provider once right after it mounts. From 0.5.0 the provider then replaces the client it destroyed with a new one, so streams, batch refreshes and plugins keep working. 0.4.0 destroys its client there for good: it keeps evaluating, with a request per flag as in poll mode, but stream and batch updates stop, and plugins get onDestroy (flaggrTelemetry() stops its periodic flushes and its Web Vitals and error capture). Production builds aren't affected.
Next.js App Router
From 0.5.0, @flaggr/sdk/react starts with a 'use client' directive, so a Server Component can render FlaggrProvider when every prop is serializable (no plugins or other functions in config). Its props reach the browser, so give it only a key that's safe there. With 0.4.0, which has no directive, or to pass such options, put the provider in a client file:
// app/providers.tsx
'use client'
import { FlaggrProvider } from '@flaggr/sdk/react'
export function Providers({ children }: { children: React.ReactNode }) {
return (
<FlaggrProvider
apiKey={process.env.NEXT_PUBLIC_FLAGGR_API_KEY}
serviceId={process.env.NEXT_PUBLIC_FLAGGR_SERVICE_ID!}
environment="production"
>
{children}
</FlaggrProvider>
)
}Render it from the root layout, which stays a Server Component:
// app/layout.tsx
import { Providers } from './providers'
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html lang="en">
<body>
<Providers>{children}</Providers>
</body>
</html>
)
}Call the hooks in Client Components (files that start with 'use client'). In Server Components and route handlers, evaluate with createFlaggr from @flaggr/sdk instead.
Hook Reference
Each hook returns the flag's value. The first render uses the value the client can resolve without a request (a streamed or bootstrapped configuration, or the cache), else the flag's defaults entry or your default. The component then re-renders with the evaluated value, and again whenever the flag changes through a stream push (updateMode: 'stream') or a batch refresh (updateMode: 'batch'). A failed evaluation resolves to the defaults entry or your default.
Every flag hook takes an optional per-call evaluation context as its last argument. The hook evaluates again when its key or default changes, not when that context object changes. So pass an object default from a constant (or useMemo), not an inline object: an inline object is a new default on every render, and the hook evaluates and subscribes again each time.
useBooleanFlag(key, defaultValue, context?)
Returns a boolean flag value.
const isEnabled = useBooleanFlag('feature-x', false)useStringFlag(key, defaultValue, context?)
Returns a string flag value.
const variant = useStringFlag('checkout-flow', 'classic')useNumberFlag(key, defaultValue, context?)
Returns a numeric flag value.
const limit = useNumberFlag('rate-limit', 100)useObjectFlag<T>(key, defaultValue, context?)
Returns a typed object flag value.
// From 0.5.0 an interface works too; 0.4.0 needs a type alias
type Config = {
maxRetries: number
timeout: number
}
// Module scope, so every render passes the same default
const API_CONFIG_DEFAULT: Config = { maxRetries: 3, timeout: 5000 }
function ApiSettings() {
const config = useObjectFlag<Config>('api-config', API_CONFIG_DEFAULT)
return <p>Retries: {config.maxRetries}</p>
}useFlag(key, defaultValue?, context?)
Evaluates a flag of any type. The return type follows the default, which is false when you leave it out.
const darkMode = useFlag('dark-mode')
const plan = useFlag('pricing-plan', 'basic')useFlaggr()
Returns the provider's client, for the methods the hooks don't cover: setContext, trackOutcome, evaluate (value, reason and variant) and the rest of the client API.
const flaggr = useFlaggr()
useEffect(() => {
flaggr.setContext({ targetingKey: user.id, plan: user.plan })
}, [flaggr, user.id, user.plan])After setContext, hooks for flags the client can evaluate locally (from a streamed or bootstrapped configuration) update at once. Other hooks keep their value until they evaluate again, for example when their key or default changes or the component remounts.
useConnectionState() and useRefreshFlags()
useConnectionState() returns the client's connection state (connecting, connected, disconnected or error) and re-renders when it changes. useRefreshFlags() returns a function that re-evaluates every flag the client has cached or a hook watches, in batched requests of up to 100 flags, re-renders the hooks whose value changed, and resolves when done. (0.4.0's only clears the client's cached values, so the next evaluation fetches again.)
Browser analytics
With @flaggr/sdk 0.5.0 and later, the values the hooks read are also published for Flaggr browser analytics (window.__FLAGGR_FLAGS__). When the provider's context has a targetingKey, a hook given a per-call context with a different targetingKey isn't published. Without one on the provider, per-call values are published. To turn publishing off, pass config={{ serviceId: 'web-app', exposeFlags: false }} to FlaggrProvider. See Browser analytics for what's published.
Patterns
Feature Gating
function Dashboard() {
const showAnalytics = useBooleanFlag('analytics-tab', false)
return (
<Tabs>
<Tab label="Overview">...</Tab>
{showAnalytics && <Tab label="Analytics">...</Tab>}
</Tabs>
)
}A/B Testing
function HeroSection() {
const variant = useStringFlag('hero-variant', 'A')
switch (variant) {
case 'A': return <HeroA />
case 'B': return <HeroB />
default: return <HeroA />
}
}Progressive Rollout
Combine percentage-based targeting in the dashboard with hooks in your code:
function CheckoutPage() {
const useNewCheckout = useBooleanFlag('new-checkout', false)
// The dashboard controls what percentage of users see this
return useNewCheckout ? <CheckoutV2 /> : <CheckoutClassic />
}Related
- TypeScript SDK — Client options, streaming, telemetry and browser analytics
- Client SDK — The client methods behind the hooks