Skip to content
FlagSwiftDocs

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#

bash
npm install @flagswift/react-native @react-native-async-storage/async-storage

It 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.

App.tsx
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.

Common options of createFlagClient
OptionTypeDescription
apiKey*stringA client key. Never use a server or admin key in an app.
baseUrl*stringYour server address, starting with http:// or https://.
environmentstringOnly for keys that cover every environment of a project.
userFlagSwiftUserWho is asking. Usually set through the provider's user prop instead.
storageadapterOffline cache, for example AsyncStorage. Without it, flags survive an outage while the app runs but not a restart while offline.
refreshIntervalmsHow often to check for changes. Default 30000. 0 turns polling off.
streamingbooleanAccepted, 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.
initialFlagsRecord<string, ClientFlag>Flags evaluated elsewhere, served from the first render.
timeout / maxRetries / initTimeoutms / number / msPer request 5000, 2 retries, and startup waits at most 5000.
autoExposuresbooleanReport an exposure the first time each outcome is read. Default false.
onErrorfunctionCalled 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.

tsx
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.

tsx
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.

tsx
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.

tsx
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.

tsx
<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.

What happens when something goes wrong
SituationDescription
A refresh failsThe 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 cachedYou get your fallbacks, then false, until the response arrives. Startup waits at most initTimeout (5 seconds).
Next launch, offlineWith storage set, the app starts with the last flags it saw, then refreshes. Without it, fallbacks apply.
Reading the stateuseFlagMeta(...).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.

tsx
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.

Exports of the React Native SDK
ExportDescription
createFlagClient(config): FlagClientCreates 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): () => voidPauses polling while the app is in the background and resumes with a refresh when it is active. Returns the unsubscribe function.