Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 91 additions & 53 deletions packages/react-native-sdk/README.md
Original file line number Diff line number Diff line change
@@ -1,72 +1,77 @@
# Reflag React Native SDK v2

React Native providers and hooks for Boolean and multivariate flags. Built on the matching React v2 SDK, with AsyncStorage persistence and a native SSE transport included.
Feature flags for React Native, built on the [React SDK](../react-sdk/README.md).

The [React SDK README](../react-sdk/README.md) covers the shared API.

## Install and initialize
## Setup

```sh
npm install @reflag/react-native-sdk
```

Requires React 17 or later (the modern JSX runtime) and a React version supported by your React Native app. Wrap your app with the React Native provider, which supplies the platform adapters:
The SDK requires React 17 or later. Wrap your app in `ReflagProvider`:

```tsx
import { ReflagProvider } from "@reflag/react-native-sdk";

<ReflagProvider
publishableKey="{YOUR_PUBLISHABLE_KEY}"
publishableKey="your-publishable-key"
context={{
user: { id: "user_123", name: "John Doe" },
company: { id: "company_123", plan: "pro" },
user: { id: "alice" },
company: { id: "acme", plan: "enterprise" },
}}
>
<App />
</ReflagProvider>;
```

Use only publishable keys in the app, never server secret keys. React Native providers default live updates on, persistence to AsyncStorage, and SSE to `react-native-sse` with transport polling disabled. `storage`, `eventSourceFactory`, and `enableLiveFlagUpdates` remain configurable.
Use your publishable key in the app. Keep secret keys on your server.

## Read flags and track usage
The provider takes the same props as the React SDK's provider. In React Native, live updates are on by default and flags are cached in AsyncStorage. Use `enableLiveFlagUpdates`, `storage` and `eventSourceFactory` to change this.

Pass a flag key to check whether it's enabled, or add a default to read another value:
## `useFlag(key, defaultValue?)`

```tsx
import { Button } from "react-native";
import { useFlag, useTrack } from "@reflag/react-native-sdk";

function StartHuddleButton() {
const enabled = useFlag("huddle");
const enabled = useFlag("huddles"); // true or false
const settings = useFlag("huddle-settings", { maxParticipants: 10 });
const track = useTrack();
if (!enabled) return null;
return (
<Button
title={`Start huddle (up to ${settings.maxParticipants})`}
title={`Start huddle (up to ${settings.maxParticipants} people)`}
onPress={() => void track("Started huddle")}
/>
);
}
```

Pass a default to read other values. The default sets the return type:

```ts
useFlag("model", "quick"); // string
useFlag("limit", 10); // number
useFlag("settings", { model: "quick" }); // { model: string }
useFlag("anything", null); // any JSON value
```

Without a default, a read expects a Boolean and returns `false` if the flag is missing or isn't a Boolean. With a default, the read returns the default while flags load, or if the flag is missing or has a different JSON type. Pass `null` to accept any JSON value, then check its type before using it.

The SDK doesn't check object fields or fill in missing fields from your default.

Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging. Track usage with `useTrack()`. `useIsLoading()` returns whether flags are still loading.

## Suspense
`useFlag()` never suspends. To wait for flags with Suspense, use `useFlagSuspense()`. For a loading UI, use `useIsLoading()`.

`useFlag()` never suspends. To wait for flags with Suspense, use `useFlagSuspense()`:
## `useFlagSuspense(key, defaultValue?)`

```tsx
import { Suspense } from "react";
import { ActivityIndicator } from "react-native";
import { useFlagSuspense } from "@reflag/react-native-sdk";

function Huddles() {
const enabled = useFlagSuspense("huddle");
const enabled = useFlagSuspense("huddles");
return enabled ? <HuddleScreen /> : null;
}

Expand All @@ -75,62 +80,74 @@ function Huddles() {
</Suspense>;
```

If a flag is missing once flags have loaded, it returns the default. The provider's `suspense` prop applies only to `useOptInFlags()`.

## Bootstrap from the server
It takes the same arguments as `useFlag()` and suspends until flags have loaded. If a flag is missing once they have, it returns the default.

Get the bootstrap data from the Node.js SDK on your server:
The provider's `suspense` prop applies only to `useOptInFlags()`.

```ts
const flags = serverClient.getFlagsForBootstrap({
user: { id: "user_123" },
company: { id: "company_123" },
});
```
## Checks, usage tracking and feedback

Pass the whole object to `ReflagBootstrappedProvider`:
Each read records a check. Reflag uses checks for exposure counts, and they show up in the Event Log, which helps with debugging.

```tsx
import { ReflagBootstrappedProvider } from "@reflag/react-native-sdk";
Track usage and send feedback with separate hooks:

<ReflagBootstrappedProvider
publishableKey="{YOUR_PUBLISHABLE_KEY}"
flags={flags}
>
<App />
</ReflagBootstrappedProvider>;
```ts
const track = useTrack();
await track("Started huddle", { button: "cta" });
const sendFeedback = useSendFeedback();
await sendFeedback({ flagKey: "huddles", score: 5 });
```

Flags are then available immediately, without a network request. With live updates on, later refreshes evaluate flags using the app's context, so values that depend on server-only attributes can change. Set `enableLiveFlagUpdates={false}` if they must not.

To use a client you create yourself, pass it to `ReflagClientProvider`. Your app is then responsible for initializing and stopping it, and for configuring its storage and live updates.

## Opt-in and feedback
The built-in feedback UI and the toolbar are web-only, so they're off in React Native. Collect feedback with your own UI and send it with `useSendFeedback()`.

`useOptInFlags()` returns the flags users can opt in to, and `useSetOptIn()` changes an opt-in. Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry.

The toolbar and built-in feedback UI are web-only and disabled by default. Collect feedback with your own UI and send it with `useSendFeedback()`.

Set `enableTracking: false` to stop sending checks and events, or `offline` to skip all requests, and reads return their defaults.
Set `enableTracking={false}` to stop sending checks and events. Set `offline` to skip all requests; reads then return their defaults.

## Optional key registration

The React Native SDK reexports React's hooks and **shares React's `Flags` registry**. Register flag types in `@reflag/react-sdk`, not a separate React Native registry:
The React Native SDK uses the React SDK's flag types, so register your flags on `@reflag/react-sdk`:

```ts
import "@reflag/react-native-sdk";

declare module "@reflag/react-sdk" {
interface Flags {
huddle: boolean;
huddles: boolean;
"huddle-settings": { maxParticipants: number };
}
}
```

Registered flags get autocompletion for their keys and type checks for the defaults you pass. The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `react` format.
Registered flags get autocompletion for their keys and type checks for the defaults you pass, in both `useFlag()` and `useFlagSuspense()`. The checks happen at compile time only. To generate the declarations, run `npx reflag flags types` with the `react` format.

## Bootstrap

## Refresh when returning to the foreground
Get the bootstrap data from the Node.js SDK on your server:

```ts
const flags = serverClient.getFlagsForBootstrap(context);
```

Pass the whole object to `ReflagBootstrappedProvider`:

```tsx
import { ReflagBootstrappedProvider } from "@reflag/react-native-sdk";

<ReflagBootstrappedProvider publishableKey="your-publishable-key" flags={flags}>
<App />
</ReflagBootstrappedProvider>;
```

Flags are then available immediately, without a network request. With live updates on, later refreshes evaluate flags using the app's context, so values that depend on server-only attributes can change. Set `enableLiveFlagUpdates={false}` if they must not.

To use a client you create yourself, pass it to `ReflagClientProvider`. Your app is then responsible for initializing and stopping it, and for configuring its storage and live updates.

## Context and loading

- `useUpdateUser()`, `useUpdateCompany()` and `useUpdateOtherContext()` return functions that merge new attributes into the current context. Changing the provider's `context` prop also updates it.
- While flags for a new context load, reads return their defaults.
- `useIsLoading()` returns whether flags are still loading.
- `useClient()` returns the underlying Browser client.

## Refresh when the app returns to the foreground

```tsx
import { useEffect, useRef } from "react";
Expand All @@ -156,7 +173,28 @@ function AppStateListener() {
}
```

Mount this listener under a React Native provider. Context prop changes and `useUpdateUser`/`useUpdateCompany`/`useUpdateOtherContext` also update evaluation context.
Render this component inside `ReflagProvider`.

## Opt-in hooks

```tsx
const { flags, isLoading } = useOptInFlags();
const setOptIn = useSetOptIn();
try {
const response = await setOptIn("huddles", { optedIn: true });
if (!response?.ok) console.error("Could not update opt-in");
} catch (error) {
console.error("Could not update opt-in", error);
}
```

Each entry includes the flag's `key`, `name`, `description` and whether the user or company has opted in. User and company opt-ins are independent, and the user or company you opt in must have an `id`. `setOptIn()` resolves once the new flag values have loaded. Check `response.ok` and catch errors, as in the example. If the list fails to load, it stays empty; call `useClient().refresh()` to retry.

Pass `{ suspense: true }` to `useOptInFlags()` to suspend until the list loads. It defaults to the provider's `suspense` prop.

## Examples

See the [Expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo) and [bare React Native](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/bare-rn) example apps.

## Migrating from v1

Expand All @@ -168,6 +206,6 @@ Mount this listener under a React Native provider. Context prop changes and `use
- If you bootstrap from the server, upgrade the Node SDK that produces the bootstrap data to v2 at the same time.
- If you generate type declarations, regenerate them with the v2 CLI.

The [Expo](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/expo) and [bare React Native](https://github.com/reflagcom/javascript/tree/main/packages/react-native-sdk/dev/bare-rn) examples use the v2 React Native APIs. The OpenFeature providers still use SDK v1.
The OpenFeature providers still use SDK v1.

See the [migration guide](https://docs.reflag.com/supported-languages/migrating-from-v1) for the full steps.
Loading