Skip to content

Latest commit

 

History

History
158 lines (113 loc) · 6.04 KB

README.md

File metadata and controls

158 lines (113 loc) · 6.04 KB

Reflag React Native SDK

A thin React Native wrapper around @reflag/react-sdk.

For more usage details, see the React SDK README.

An Expo example app lives in packages/react-native-sdk/dev/expo.

Get started

Install

npm i @reflag/react-native-sdk

1. Add the ReflagProvider

Wrap your app with the provider from @reflag/react-native-sdk:

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

<ReflagProvider
  publishableKey="{YOUR_PUBLISHABLE_KEY}"
  context={{
    user: { id: "user_123", name: "John Doe", email: "john@acmeinc.com" },
    company: { id: "company_123", name: "Acme, Inc", plan: "pro" },
  }}
>
  {/* children here are shown when loading finishes */}
</ReflagProvider>;

2. Use useFlag(<flagKey>)

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

function StartHuddleButton() {
  const isEnabled = useFlag("huddle"); // true or false
  const track = useTrack();

  if (!isEnabled) return null;

  return <Button title="Start huddle" onPress={() => void track("huddle")} />;
}

To read a multivariate flag, pass a default, such as useFlag("huddle-settings", { maxParticipants: 10 }). The default sets the return type.

See the React SDK README for more details.

React Native differences

  • The Reflag toolbar is web-only and is not available in React Native.
  • Built-in feedback UI is web-only. In React Native, use your own UI and call useSendFeedback or client.feedback when you're ready to send feedback.
  • Live flag updates work out of the box. The React Native SDK bundles an SSE transport via react-native-sse, so no global EventSource shim is required.
  • If you need custom SSE behavior, you can still override the transport by passing eventSourceFactory to ReflagProvider or ReflagBootstrappedProvider.

Reference

The React Native SDK shares its API with the React SDK. Use the React SDK reference for full types and details:

React SDK Reference

Cookbook

Refresh flags when the app returns to the foreground

Flags are updated if the context passed to <ReflagProvider> changes, but you might also want to update them when the app comes to the foreground. See this snippet:

import React, { useEffect, useRef } from "react";
import { AppState } from "react-native";
import { ReflagProvider, useClient } from "@reflag/react-native-sdk";

function AppStateListener() {
  const client = useClient();
  const appState = useRef(AppState.currentState);

  useEffect(() => {
    const subscription = AppState.addEventListener("change", (nextAppState) => {
      if (
        appState.current.match(/inactive|background/) &&
        nextAppState === "active"
      ) {
        void client.refresh();
      }
      appState.current = nextAppState;
    });

    return () => subscription.remove();
  }, [client]);

  return null;
}

export function App() {
  return (
    <ReflagProvider publishableKey="{YOUR_PUBLISHABLE_KEY}">
      <AppStateListener />
      <MyApp />
    </ReflagProvider>
  );
}

Suspense loading

useFlag() never suspends. To use <Suspense>, read flags with useFlagSuspense(), which takes the same arguments as useFlag(), and wrap the components that call it in a Suspense boundary:

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

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

<ReflagProvider publishableKey="{YOUR_PUBLISHABLE_KEY}">
  <Suspense fallback={<ActivityIndicator />}>
    <Huddles />
  </Suspense>
</ReflagProvider>;

The provider's suspense prop only applies to useOptInFlags().

Bootstrapping

You can use <ReflagBootstrappedProvider> in React Native when you already have pre-fetched flags and want to avoid an initial fetch. Pass the full object returned by the Node SDK's getFlagsForBootstrap() directly as the provider's flags prop; it includes protocolVersion, context, evaluated flags, and an optional flagStateVersion.

Use @reflag/node-sdk v2 to produce the bootstrap data. It only includes flags marked as not secret (secret: false), and the app can read the context you bootstrap, so leave out secrets and server-only attributes.

After bootstrapping, any live flag updates are fetched directly by the client SDK from Reflag using the client-visible context. If your bootstrapped snapshot depends on server-only or secret context that is not available in the app, later live refreshes may differ. In that case, keep enableLiveFlagUpdates disabled.

For bootstrap usage patterns and options, see the React SDK bootstrapping docs.

Migrating from v1

  • useFlag() returns the flag's value: replace const { isEnabled } = useFlag(key) with const isEnabled = useFlag(key).
  • Move remote config to a multivariate flag and read it with a default, such as useFlag("model", "quick"). Existing remote config isn't converted automatically.
  • Use useTrack() instead of the flag's track(), and send feedback with useSendFeedback().
  • Replace useFlag(key, { suspense: true }) with useFlagSuspense(key), and the flag's isLoading property with useIsLoading().
  • useFeature() is removed. Use useFlag() instead.
  • Use the setOptIn function returned by useOptInFlags(). useSetOptIn() still works but is deprecated.
  • Opt-in entries have a Boolean value instead of isEnabled.
  • Remove fallbackFlags and pass a default to each read instead, such as useFlag("huddle", true).
  • 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.

See the migration guide for the full steps.