React SDK
A provider and hooks that tell a React app which flags are on for the person using it. The server decides, so no targeting rules reach the browser.
Use this SDK in single-page apps and client components. For server components and middleware, see the Next.js SDK. It is built on the core client, so every method there also works here. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
npm install @flagswift/react- Requires
- React 18+
- Key
- Client key (fs_client_)
- Evaluates
- On the server, for one person
- Real-time updates
- Yes
- Works offline from
- localStorage cache
- Outcome analytics
- Yes
- Verified
- Unit tests
Options, user context and behaviour every SDK shares are on Options and behaviour. To compare SDKs, see SDK features.
Installation#
npm install @flagswift/reactIt needs React 18 or newer. The hooks read the client through useSyncExternalStore, so components re-render when a flag changes.
Initialization#
You need a client key (fs_client_…) from the API Keys page and the address of your FlagSwift server. Create the client once, outside any component, and wrap your app in the provider.
import { FlagClient, FlagProvider } from "@flagswift/react";
const client = new FlagClient({
apiKey: process.env.NEXT_PUBLIC_FLAGSWIFT_KEY!, // a client key: fs_client_...
baseUrl: "https://flags.example.com", // your FlagSwift server
environment: "production", // only for project-wide keys
});
export const Providers = ({ user, children }) => (
<FlagProvider
client={client}
user={{ identifier: user?.id, account: user?.orgId, attributes: { plan: user?.plan } }}
>
{children}
</FlagProvider>
);Safe under StrictMode
<FlagProvider> starts the client on mount and stops it on unmount. React's second mount in development restarts it, so you do not need to guard anything.Connection options#
apiKey and baseUrl are required. Everything else has a default.
| Option | Type | Description |
|---|---|---|
| apiKey* | string | A client key. Never use a server or admin key in a browser. |
| baseUrl* | string | Your server address, starting with http:// or https://. |
| environment | string | Only for keys that cover every environment of a project. |
| user | FlagSwiftUser | Who is asking. Usually set through the provider's user prop instead. |
| refreshInterval | ms | How often to check for changes. Default 30000. 0 turns polling off. |
| streaming | boolean | Keep one real-time connection open so changes arrive at once. Default false. |
| fallbacks | { [flag]: value } | Served until flags load, and for flags the server does not know. |
| initialFlags | Record<string, ClientFlag> | Server-evaluated flags for a first render with no flicker. |
| overrides | Record<string, FlagOverride> | Runtime-only values for local tests. Never sent to Enterprise. |
| storage | adapter | false | Offline cache. localStorage by default, never on the server. false turns it off. |
| timeout / maxRetries | ms / number | Per request, default 5000 and 2 retries. |
| autoExposures | boolean | Report an exposure the first time each outcome is read. Default false. |
| onError | function | Called when a refresh fails. Flags stay as they were. |
| warnOnMissingFlag | boolean | Log one console warning per flag name that is not found once flags have loaded, so a misspelled name is noticed while you build. Not logged for a flag that has a fallback. Default true. |
Developer toolbar#
Use <DeveloperToolbar> inside <FlagProvider> while building. It lists loaded flags, lets you force a local outcome, restores the server value and lets you try another user, account or device context.
import { DeveloperToolbar, FlagProvider } from "@flagswift/react";
<FlagProvider client={client}>
<App />
<DeveloperToolbar />
</FlagProvider>Development only
NODE_ENV is production. You can also pass enabled=. Overrides stay in the client instance and never update the Enterprise console. isKillSwitchEnabled ignores them on purpose, so a kill can never be masked.| API | Description |
|---|---|
| useIsKillSwitchEnabled(key) | True when the server has disabled the flag with its kill switch. Local overrides are ignored on purpose. |
| useFlagMeta(key).killSwitchActive | Kill-switch state alongside enabled, loading, error, variant and value. |
| client.setOverride / clearOverride / clearOverrides | Apply or remove local runtime values for custom test tooling. |
Check flags#
To check whether a flag is on, call useFlag. The second argument is what to use until flags load. Without it you get false.
import { useFlag } from "@flagswift/react";
export const Dashboard = () => {
const enabled = useFlag("new-dashboard");
return enabled ? <NewDashboard /> : <OldDashboard />;
};To show or hide a block without a condition in your code, use <Feature>.
import { Feature } from "@flagswift/react";
<Feature flag="beta-banner" fallback={<StandardBanner />}>
<BetaBanner />
</Feature>Check variants and values#
A flag with variants serves one named variant to each person. Every variant has a key (its name in the console, such as a) and a value (what it carries, such as "hello"). useVariant returns the key. useFlagValue returns the value. Mixing them up is the most common surprise: a string flag whose variant a holds "hello" logs "a" from useVariant, not "hello".
import { useFlagMeta, useFlagValue, useVariant } from "@flagswift/react";
// Flag "fx-string" has two variants: a = "hello", b = "goodbye"
export const Greeting = () => {
const variant = useVariant("fx-string"); // "a" the variant KEY
const text = useFlagValue<string>("fx-string", ""); // "hello" the variant VALUE
const meta = useFlagMeta("fx-string"); // { enabled, loading, error, variant: "a", value: "hello" }
console.log(variant, text, meta.variant, meta.value);
// "a" "hello" "a" "hello"
return <h1>{text}</h1>;
};| Hook | Returns | Description |
|---|---|---|
| useVariant(name) | string | undefined | The variant key, such as "a". undefined before flags load or for unknown and plain flags. |
| useFlagValue(name, fallback?) | T | The variant value, such as "hello" (the boolean for plain flags). Before load or for unknown flags: fallback, then the client's fallbacks. |
| useFlagMeta(name) | FlagMeta | enabled, loading, error, plus variant (the key) and value when the flag has variants. |
Good to know
useVariant is not undefined for a disabled flag with variants; check useFlag if you need on or off. It is undefined only for plain flags, unknown flags, or before the first load.import { useFlagValue, useVariant } from "@flagswift/react";
export const Checkout = () => {
const variant = useVariant("checkout-layout"); // "compact" | "wide" | undefined
const limit = useFlagValue<number>("seat-limit", 5); // the variant's value, or 5
if (variant === "compact") return <CompactCheckout limit={limit} />;
return <WideCheckout limit={limit} />;
};Defer rendering until flags load#
useFlagMeta tells you whether the first response has arrived, so you can show a skeleton instead of a flash of the wrong version.
import { useFlagMeta } from "@flagswift/react";
export const Pricing = () => {
const { enabled, loading, error } = useFlagMeta("new-pricing");
if (loading) return <PricingSkeleton />;
if (error) console.warn("Using last known flags:", error);
return enabled ? <NewPricing /> : <OldPricing />;
};No flash at all
initialFlags. With the Next.js SDK that is one call, and the first paint is already correct.Change the person#
The provider calls identify whenever its user prop changes (compared by value), so a login, logout or tenant switch re-evaluates every flag. To do it yourself, use the client.
import { useFlagSwift } from "@flagswift/react";
const SwitchAccount = ({ account }: { account: string }) => {
const client = useFlagSwift();
return (
<button onClick={() => client.identify({ identifier: "user-123", account })}>
Switch to {account}
</button>
);
};Offline, identify uses that person's cached flags if there are any, and otherwise keeps the previous flags rather than dropping to fallbacks.
If you already hold the new person's flags, for example evaluated on the server, pass them: identify(user, { flags }) shows them at once as bootstrap and then refreshes. The same user keeps its bootstrap or network flags rather than a stale cache, and getUser() returns the person being evaluated. From an identify without flags until the new person's flags arrive, automatic exposures are not reported and an explicit trackExposure is skipped, so an exposure is never credited to the wrong user.
Real-time updates#
By default the client polls. Set streaming: true and a flag change reaches the page within moments. The stream carries only a note that something changed, never flag data, and the key travels in a header.
const client = new FlagClient({ apiKey, baseUrl, streaming: true });If the stream drops, polling returns to its normal rate at once instead of waiting out the slower interval. If streaming is off on the server, or the connection cannot be kept, the client settles on polling. Flags keep working either way. client.getHealth().streaming reports off, connecting, connected or unavailable.
Offline and errors#
Once flags have loaded, the app keeps working with no internet and through a server outage. Checks read from memory, never touch the network and never throw.
| Situation | Description |
|---|---|
| A refresh fails | The last good flags stay. The error is set, onError is called, and polling backs off up to five minutes. The next success clears it. |
| First load, nothing cached | You get your fallbacks, then false, until the response arrives. Startup waits at most initTimeout (5 seconds). |
| Next page load, offline | The flags saved in localStorage apply at once, so the page is correct before the network answers. |
| A flag name that does not exist | useFlag returns your fallback (then false), the console logs one warning per name after flags load, and the miss is counted as FLAG_NOT_FOUND on the Errors page. Check the spelling: names are case-sensitive. |
| Reading the state | useFlagMeta(...).error, or client.getState() for status, source and lastUpdated. |
Outcome analytics#
Report what people saw and what they did so FlagSwift can compare variants. Nothing is sent unless you call these or turn autoExposures on, and only the person's identifier, the flag, the variant and the event name leave your app.
const client = useFlagSwift();
client.trackExposure("checkout-redesign"); // this person was shown the flag's current outcome
await client.track("purchase", 49.9); // what they did, with an optional valueAt most 500 events wait in the queue. Once it is full, new ones are dropped silently (the ones already queued are kept) and counted in client.getHealth().analytics.dropped.
See Outcomes for how results are read in the console.
Reference#
| Export | Description |
|---|---|
| new FlagClient(config) | A client. Extra options: storage (localStorage by default, never on the server; false turns it off), userIdentifier (a shorthand used only when user is not set), sdk. |
| <FlagProvider client user?> | Starts the client on mount and destroys it on unmount. Safe under StrictMode: the second mount restarts the client. Calls identify when user changes (compared by value). |
| useFlagSwift(): FlagClient | The client. Throws outside a provider. |
| useFlag(flagName, fallback?): boolean | On or off. Gives the fallback (then false) until flags load. |
| useVariant(flagName): string | undefined | The served variant KEY (for example "a"), not its value. |
| useFlagValue<T>(flagName, fallback?): T | The variant VALUE (for example "hello"), or the boolean for plain flags. |
| useFlagMeta(flagName) | enabled, loading, error (string), killSwitchActive, variant and value. |
| useIsKillSwitchEnabled(flagName) | Whether the server kill switch is active for the flag. |
| useFlagContext() | isEnabled(name), isKillSwitchEnabled(name), loading, error, flags and client. |
| <DeveloperToolbar enabled?> | Local flag and evaluation-context controls for development and testing. |
| <Feature flag fallback?> | Renders its children when the flag is on, otherwise fallback (default nothing). |
Segments from your own code#
Put segment keys on the user and they count as extra segment membership: a flag that targets segment beta is turned on for a user who passes segments: ["beta"], even if the segment has no members or rules of its own in FlagSwift. Segments only decide on or off, so a kill switch or a disabled flag still wins, and variants are still chosen by the flag's allocation weights when it is on and its off variant when it is off. Changing the segments re-evaluates the flags.
<FlagProvider client={client} user={{ identifier: user.id, segments: ["beta", "staff"] }}>
<App />
</FlagProvider>
// or later: client.identify({ identifier: user.id, segments: ["beta"] })Trusted input