React Native SDK
Expo and bare apps, with an offline cache and background pause. The server decides, so no targeting rules reach the device.
This SDK has the same hooks as the React SDK, plus an on-device cache and background pause, and it re-exports everything from it. It is built on the core client. Options and behaviour every SDK shares are on Options and behaviour.
At a glance#
- Install
npm install @flagswift/react-native- Requires
- React Native 0.70+, AsyncStorage for the cache
- Key
- Client key (fs_client_)
- Evaluates
- On the server, for one person
- Real-time updates
- No, it polls
- Works offline from
- Storage adapter (AsyncStorage)
- 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/react-native @react-native-async-storage/async-storageIt uses only fetch and AbortController, with no native modules of its own. AsyncStorage is optional but recommended, because it is what keeps flags across restarts.
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 FlagSwiftProvider.
import AsyncStorage from "@react-native-async-storage/async-storage";
import { createFlagClient, FlagSwiftProvider, useFlag } from "@flagswift/react-native";
const client = createFlagClient({
apiKey: process.env.EXPO_PUBLIC_FLAGSWIFT_KEY!, // a client key: fs_client_...
baseUrl: "https://flags.example.com", // your FlagSwift server
storage: AsyncStorage, // last good flags survive restarts
fallbacks: { "new-onboarding": false },
});
export default function App() {
return (
<FlagSwiftProvider client={client} user={{ identifier: userId, device: deviceId }}>
<Home />
</FlagSwiftProvider>
);
}
const Home = () => (useFlag("new-onboarding") ? <NewOnboarding /> : <Onboarding />);Background pause is built in
FlagSwiftProvider wraps the React provider and also calls bindAppState for you, so polling stops while the app is in the background.Connection options#
apiKey and baseUrl are required. Everything else has a default. createFlagClient takes the same options as the React FlagClient.
| Option | Type | Description |
|---|---|---|
| apiKey* | string | A client key. Never use a server or admin key in an app. |
| 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. |
| storage | adapter | Offline cache, for example AsyncStorage. Without it, flags survive an outage while the app runs but not a restart while offline. |
| refreshInterval | ms | How often to check for changes. Default 30000. 0 turns polling off. |
| streaming | boolean | Accepted, but React Native's fetch cannot read a response as it arrives, so it settles on unavailable and the client keeps polling. |
| fallbacks | { [flag]: value } | Served until flags load, and for flags the server does not know. |
| initialFlags | Record<string, ClientFlag> | Flags evaluated elsewhere, served from the first render. |
| timeout / maxRetries / initTimeout | ms / number / ms | Per request 5000, 2 retries, and startup waits at most 5000. |
| 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. |
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, Feature } from "@flagswift/react-native";
const Home = () => {
const enabled = useFlag("new-onboarding");
return enabled ? <NewOnboarding /> : <Onboarding />;
};
// Or without a condition in your code
<Feature flag="beta-banner" fallback={<StandardBanner />}>
<BetaBanner />
</Feature>Check variants and values#
useVariant gives the served variant's key and useFlagValue gives what it carries. useFlagMeta adds loading and error, so you can show a placeholder instead of the wrong screen.
import { useFlagMeta, useFlagValue, useVariant } from "@flagswift/react-native";
const Paywall = () => {
const variant = useVariant("paywall-layout"); // "compact" | "wide" | undefined
const trialDays = useFlagValue<number>("trial-days", 7); // the variant's value, or 7
const { loading } = useFlagMeta("paywall-layout");
if (loading) return <Splash />;
return variant === "compact" ? <CompactPaywall days={trialDays} /> : <WidePaywall days={trialDays} />;
};Change the person#
The provider calls identify whenever its user prop changes, so a login or logout re-evaluates every flag. Pass device for a per-install identifier: a flag that buckets by device then stays stable for that install, even before login.
import { useFlagSwift } from "@flagswift/react-native";
const client = useFlagSwift();
await client.identify({ identifier: "user-123", device: deviceId });Offline, identify uses that person's cached flags if there are any, and otherwise keeps the previous flags rather than dropping to fallbacks.
Background and foreground#
Polling pauses while the app is backgrounded, so a phone in a pocket does not wake the radio every 30 seconds, and a refresh runs when the app is active again. FlagSwiftProvider does this for you. If you build the provider yourself, bind it by hand.
import { AppState } from "react-native";
import { bindAppState } from "@flagswift/react-native";
const unbind = bindAppState(client, AppState); // pause when not active, resume and refresh when active
// later: unbind();Developer toolbar#
Render <DeveloperToolbar /> once inside <FlagSwiftProvider> to inspect flags, force one on or off on this device only, and try another user. It shows only in debug builds (__DEV__) and uses native views, so it works in Expo and bare apps.
<FlagSwiftProvider client={client}>
<Navigation />
<DeveloperToolbar position="bottom-left" />
</FlagSwiftProvider>See the developer toolbar guide for the options.
Real-time updates#
React Native's fetch cannot read a response as it arrives, so streaming: true settles on unavailable and the client keeps polling. Everything else works as usual. Flag changes arrive on the next poll, within refreshInterval (30 seconds by default).
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 launch, nothing cached | You get your fallbacks, then false, until the response arrives. Startup waits at most initTimeout (5 seconds). |
| Next launch, offline | With storage set, the app starts with the last flags it saw, then refreshes. Without it, fallbacks apply. |
| 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 the device.
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 value
await client.flushAnalytics(); // send what is queued now (optional)See Outcomes for how results are read in the console.
Reference#
Everything from the React SDK is re-exported, plus the following.
| Export | Description |
|---|---|
| createFlagClient(config): FlagClient | Creates a client that identifies as react-native. Pass storage (for example AsyncStorage) so the app starts with correct flags offline. |
| <FlagSwiftProvider client user?> | The React provider, re-exported under the React Native package. |
| bindAppState(client, AppState): () => void | Pauses polling while the app is in the background and resumes with a refresh when it is active. Returns the unsubscribe function. |