React Native SDK
Introduction
The React Native SDK is intended to be used by React Native mobile applications.
The minimum supported version of React Native is 0.75, and the minimum supported version of Expo is 52.
Installation
The SDK can be installed from NPM: https://www.npmjs.com/package/@configdirector/react-native-sdk
npm install --save @configdirector/react-native-sdk
yarn add @configdirector/react-native-sdk
pnpm add @configdirector/react-native-sdk
bun add @configdirector/react-native-sdk
Also install @react-native-async-storage/async-storage, which works in Expo Go. Without it, the SDK cannot tell one app start from a new install: every start counts as one more monthly active user, nothing is kept on the device for the next start, and the SDK logs a warning.
npm install --save @react-native-async-storage/async-storage
yarn add @react-native-async-storage/async-storage
pnpm add @react-native-async-storage/async-storage
bun add @react-native-async-storage/async-storage
npx expo install @react-native-async-storage/async-storage
Configure and initialize the provider
Initialize the provider with your client SDK key:
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0">
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
};
Additional configuration options
These configuration options can be passed in to the ConfigDirectorProvider.
appName and appVersion
The appName and appVersion props allow you to provide your application's name and version. These values can be used in targeting rules conditionals. For example, if a certain feature should only be enabled starting with a certain version of your application.
React Native itself does not expose the app name or version, so whichever of the two you leave unset is read from expo-application or react-native-device-info when your app has either installed. Without one of those modules, set both props if you intend to target on them; the SDK says which one it could not find at the info log level.
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0">
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
};
context
The context to be used during targeting rules evaluation:
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0"
context={{ id: "12345", name: "Example User", traits: { region: "North America" } }}>
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
}
logger
By default, the SDK logs to the console and it is set to log warnings and errors only. You can configure a logger by either creating a ConfigDirector console logger with a different log level, or by implementing the ConfigDirectorLogger interface to provide your own logger. The interface can be used to create an adapter to another logging library.
Configure the ConfigDirector console logger to a different level:
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider, createConsoleLogger } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0"
logger={createConsoleLogger("debug")}>
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
}
Implement your own logger adapter:
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider, ConfigDirectorLogger } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0"
logger={myLogger}>
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
}
netInfoSubscribe
Allows providing a subscription function with the same signature as NetInfo.addEventListener from @react-native-community/netinfo. This options can be used to enable immediate reconnection when the device regains network connectivity instead of waiting for the next exponential-backoff retry.
For example, if a user lost network connectivity for several minutes, once they regain network connectivity there may still be a delay of minutes for the exponential backoff retry to catch up. In most cases, this is not needed and the standard retry with exponential backoff is sufficient. However, if your use case needs immediate reconnection, this can be a useful option.
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider, ConfigDirectorLogger } from "@configdirector/react-native-sdk";
import NetInfo from '@react-native-community/netinfo';
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0"
netInfoSubscribe={NetInfo.addEventListener}>
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
};
mode
The connection mode, which can be streaming, polling or offline. It is recommended to use the default of streaming unless you have a specific need to use polling instead. Defaults to streaming.
Set mode to offline to run your application without connecting to ConfigDirector, for example in a suite of UI tests where each run pins every flag to a known value. An offline provider needs no sdkKey, opens no connection and sends nothing, so the application is invisible to the ConfigDirector dashboard: no evaluations are counted and no lifecycle state changes. Every context receives the same value and targeting rules are not applied.
Give the values in the values prop, with one value per config key. Your application decides where they come from, for example a module bundled with the test build:
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider mode="offline" values={{ "new-checkout": true, "max-items": 20 }}>
<YourApp />
</ConfigDirectorProvider>
);
}
The config type of each value follows from the value itself: a boolean, an integral number (integer), any other number (float), a string, or an object or array (json). A value read with an in-code default value of another type returns the in-code default value, as it does against ConfigDirector. The status turns ready right after the provider mounts, and a new context keeps the same values. Returning to the foreground or regaining the network opens no connection. values can be given only in offline mode, and pollingInterval, timeout and url have no effect in it.
With mode="offline" and no values, the provider is ready at once and every config returns its in-code default value.
When the values cannot be loaded, because of a value such as null or because values is given in streaming or polling mode, the client never becomes ready: every config returns its in-code default value, the status stays loading, and the provider reports a ConfigDirectorInitializationError as an unhandled promise rejection.
If you come from LaunchDarkly, a map of values is what LaunchDarkly calls "flags from files", and offline with no values is its "offline mode".
values
The values to serve in offline mode, one value per config key. It can be given only in offline mode; see mode.
pollingInterval
The interval, in seconds, between requests for config updates when mode is polling. It has no effect in streaming mode. A value below the minimum of 30 seconds is raised to 30 seconds and a warning is logged. Defaults to 60 seconds. See Polling intervals.
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider sdkKey="YOUR-CLIENT-SDK-KEY" mode="polling" pollingInterval={120}>
<YourApp />
</ConfigDirectorProvider>
);
}
url
The base URL used to connect to ConfigDirector services. This should only be provided if your environment requires you to configure a proxy server in order to connect to ConfigDirector services.
Values kept on the device
By default, the client keeps the last values it received from ConfigDirector in AsyncStorage, and serves them on the next launch of the same context until live values arrive. An application opened without a network, after at least one successful connection, shows the values ConfigDirector last sent instead of the default values provided in code. Every evaluation served this way reports the reason cached, with isDefaultValue set to false.
The client is not ready while it serves values kept on the device: the status stays loading until the provider's initialization completes with live values or its timeout, then default, and ready once live values arrive and replace them. The cachedValuesLoaded hook fires when the kept values are loaded, together with configsUpdated listing their keys, so watchers and hooks pick them up.
The values are kept for the context they were evaluated for, and served on the next launch only when the launch context has the same kind and id. A launch with another context serves the in-code default values until live values arrive, which then replace the kept values. A context without an id matches on the same install, as long as the app has not been uninstalled, because ConfigDirector derives its identifier from the instance ID the SDK stores; a context without an id keeps its percentage rollout bucket for as long as that instance ID lasts. Name, traits, app name and app version take no part in the match: live values correct them within a second when there is a network. Once the client is running, updating the context keeps serving the current values until the new context's values arrive, as it does with live values.
Turn it off, or supply your own store, with the caching prop:
enabled- Whether to keep the last values received. With
false, nothing is read or written, even when aprovideris given. - Defaults to
true
- Whether to keep the last values received. With
provider- A store of your own, for example an encrypted one, implementing
CachingProvider:read()returns the stored entry orundefined,write(value)replaces it,remove()deletes it, andsizeLimit()returns the largest entry, in bytes, the store accepts. Each ofread,writeandremovemay return a promise. One provider instance serves one client. - Defaults to AsyncStorage, under a key derived from the client SDK key, with a size limit of 256 KB
- A store of your own, for example an encrypted one, implementing
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider sdkKey="YOUR-CLIENT-SDK-KEY" caching={{ enabled: false }}>
<YourApp />
</ConfigDirectorProvider>
);
}
The entry is one string whose format belongs to the SDK and may change between SDK versions; an entry a newer SDK cannot read is removed. Before every write the SDK measures the entry against sizeLimit(); above it, the entry is removed and a warning is logged once, so the device never serves values that no longer reflect the set. A provider that fails to read, write or remove is logged once and never stops the client: the worst outcome is the in-code default values. Keeping values on the device is ignored in offline mode. Without @react-native-async-storage/async-storage installed, the SDK logs one warning and keeps nothing on the device, as it keeps no instance ID.
Retrieve config values
Retrieve a config value with the useConfigValue hook:
import { useConfigValue } from "@configdirector/react-native-sdk";
function YourComponent() {
const { value } = useConfigValue("my-config-key", false);
return <p>my-config-key: {value}</p>;
}
export default YourComponent;
You can also determine if the client is still initializing. This can be useful in the event of a slow connection where retrieving the initial config values may be slow, so rather than transition from the in-code default value to the evaluated value, you can show a loading state until the client is ready and config values are evaluated:
import { useConfigValue } from "@configdirector/react-native-sdk";
function YourComponent() {
const { value, loading } = useConfigValue("my-config", "default value");
if (loading) {
return <p>Loading...</p>;
} else {
return <p>My config value: {value}</p>;
}
}
export default YourComponent;
Update the context
The app connects with the context given to the provider's context prop. Give it there when you already know the context as the app starts, so the first connection carries it:
import { View } from "react-native";
import AwesomeApp from "./AwesomeApp";
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
export default function App() {
return (
<ConfigDirectorProvider
sdkKey={"YOUR-CLIENT-SDK-KEY"}
appName="MyAwesomeApp"
appVersion="1.0.0"
context={{ id: "12345", name: "Example User", traits: { region: "North America" } }}>
<View>
<AwesomeApp />
</View>
</ConfigDirectorProvider>
);
};
To change the context afterwards, for example when a user signs in, call updateContext from the useContext hook where the change happens. Each updateContext call opens a new connection with the new context:
import { Button, Text, View } from "react-native";
import { useConfigValue, useContext } from "@configdirector/react-native-sdk";
function YourComponent() {
const { value } = useConfigValue("my-config-key", false);
const { updateContext } = useContext();
const onUpdate = async () => {
await updateContext({
id: "654321",
name: "Another User",
traits: {
region: "Australia",
},
});
};
return (
<View>
<Text>my-config-key: {String(value)}</Text>
<Button title="Update context" onPress={onUpdate} />
</View>
);
}
export default YourComponent;
Rendering the provider with a different context prop updates the context the same way.
To evaluate configs for an entity other than a user, such as a tenant, set the context kind with kind:
updateContext({
id: "acme",
kind: "tenant",
name: "Acme Inc.",
traits: {
plan: "enterprise",
},
});
Leaving kind out means user. A context kind is 1 to 64 lowercase letters, digits, dashes, or underscores. A context with an invalid context kind is ignored: the SDK logs an error, and configs are evaluated as if no context had been given. Context kinds are available from version 1.7.0 of the SDK.
With @react-native-async-storage/async-storage installed, the SDK keeps an instance ID in AsyncStorage until the app is uninstalled, and ConfigDirector derives the identifier of a context without an id from it. A person who uses the app without signing in keeps that identifier, and their percentage rollout bucket, from one app start to the next, and counts as one monthly active user however often they open the app.
useClient hook
In the event that you need to have access to the underlying Javascript ConfigDirectorClient instance for more complex behaviors, you can access the instance via the useClient hook:
import { useClient } from "@configdirector/react-native-sdk";
function YourComponent() {
const { client } = useClient();
// Utilize the client for more involved logic
return <p>A more complex component</p>;
}
export default YourComponent;
useClient hook. The useConfigValue and useContext hooks manage listeners and cleanup automatically. However, if you make use of the useClient hook, you must manage cleaning up any listeners yourself.Additionally, any calls to
dispose, unwatch, or unwatchAll on the client instance can have unintended side effects and may result in subtle bugs.evaluate
The client's evaluate(key, defaultValue) reads a config the way useConfigValue does and returns the evaluation behind the value: the value, whether it is the in-code default value, the reason, the valueId, and the variation. The JavaScript SDK describes it. Use it where the reason matters at the point of the read, such as when reporting an evaluation to another system. It reads once and does not re-render the component when the value changes, so keep rendering with useConfigValue. The SDK exports the ConfigEvaluation, EvaluationReason and Variation types. evaluate is available from version 1.10.0, and its variation from version 1.11.0.
import { Button } from "react-native";
import { useClient } from "@configdirector/react-native-sdk";
function CheckoutButton() {
const { client } = useClient();
const startCheckout = () => {
const evaluation = client.evaluate("new-checkout", false);
analytics.track("checkout-started", { newCheckout: evaluation.value, reason: evaluation.reason });
};
return <Button title="Check out" onPress={startCheckout} />;
}
track
The client's track(eventName, options) reports to ConfigDirector that something happened for the current context, such as a completed checkout, so ConfigDirector can show it on the Live feed and count it for each variation of a running experiment. options is optional and takes a value, a number the event measures, and details, an object describing the event. An event counts for an experiment only when the current context has an id. The JavaScript SDK describes the options and the limits. track is available from version 1.11.0.
import { Button } from "react-native";
import { useClient } from "@configdirector/react-native-sdk";
function PayButton() {
const { client } = useClient();
const pay = async () => {
const order = await submitOrder();
client.track("checkout-completed", { value: order.total, details: { plan: order.plan } });
};
return <Button title="Pay" onPress={pay} />;
}
Test your components
Use the SDK's testing entry point, @configdirector/react-native-sdk/testing, to test components that read your configs and flags. It creates a test client: the SDK's real client connected to an in-memory server that your test controls. Only the connection to ConfigDirector is replaced. Everything else is the same code that runs in production, including ConfigDirectorProvider and the hooks, so your components behave exactly as they do against ConfigDirector, and no network connection is opened and no telemetry is sent.
Render the production ConfigDirectorProvider with its client prop:
import { act, render } from "@testing-library/react-native";
import { ConfigDirectorProvider } from "@configdirector/react-native-sdk";
import { createTestClient } from "@configdirector/react-native-sdk/testing";
import { Home } from "./Home";
test("shows the new checkout when the flag is on", async () => {
const testClient = createTestClient({ values: { "new-checkout": true } });
const view = await render(
<ConfigDirectorProvider client={testClient.client}>
<Home />
</ConfigDirectorProvider>,
);
await view.findByText("New checkout");
await act(() => testClient.setValue("new-checkout", false));
view.getByText("Classic checkout");
});
The provider renders its children before initialization completes, so the first assertion uses findBy… rather than getBy…. Wrap setValue, removeValue, and replaceValues in act(), since they re-render the components under the provider at once. React Native Testing Library 14 made render, fireEvent, and act asynchronous, so the examples await them; the same code works with version 13, where they return at once.
Components that render their own provider
An App component that renders <ConfigDirectorProvider sdkKey="…"> itself would build a real client. installTestClient makes every provider mounted without a client prop use the test client instead:
import { createTestClient, installTestClient } from "@configdirector/react-native-sdk/testing";
let testClient: TestClient;
let uninstallTestClient: () => void;
beforeEach(() => {
testClient = createTestClient({ values: { "new-checkout": true } });
uninstallTestClient = installTestClient(testClient);
});
afterEach(() => uninstallTestClient());
test("renders the app with the flag on", async () => {
const view = await render(<App />);
await view.findByText("New checkout");
});
While installed, the provider's construction props (sdkKey, url, mode, values, timeout, pollingInterval, logger, appName, appVersion) are ignored; context, hooks, and netInfoSubscribe apply as they do with a client prop. In an Expo Router app, renderRouter from expo-router/testing-library renders the root layout that builds the provider, so the whole app runs on the installed test client. A provider reads the installed client when it is constructed, so install before rendering. Installing again replaces the installed test client, and each uninstall function restores the one installed before it.
What the provider does with a given client
- It never disposes a client it was given, whether through the
clientprop orinstallTestClient. It disposes only a client it built from its own props. - It does not call
initializeon a client that is ready or initializing. If the client is ready and thecontextprop is given and differs from the client's context, it callsupdateContext. A provider given a ready client reports thereadystatus on its first render. hooksgiven with aclientare registered on it while the provider is mounted and removed when it unmounts, like every other handler the provider registers, and so are itsAppStateand NetInfo subscriptions, even when it unmounts beforeinitializeresolves.- The
contextprop is compared by deep equality, on mount and on later renders, so a new object with the same contents does not reconnect. - A
clientprop that changes after the provider mounted is ignored with a warning. Remount the provider, for example with a newkey, to use another client.
Jest setup
The package and its dependency @noble/hashes are ES modules, and the package's files are .mjs files, which neither the jest-expo nor the @react-native/jest-preset preset transforms: their Babel transform only covers .js, .ts, and .tsx files. The Jest configuration needs two additions: transformIgnorePatterns that let Jest transform both packages, and a transform entry that applies the preset's Babel transform to .mjs files.
Since React Native 0.86, the React Native Jest preset is its own package, @react-native/jest-preset, and jest-expo requires it as a peer dependency. Install it next to your test runner:
npm install --save-dev @react-native/jest-preset
yarn add --dev @react-native/jest-preset
pnpm add --save-dev @react-native/jest-preset
bun add --dev @react-native/jest-preset
For an Expo app:
const expoPreset = require("jest-expo/jest-preset");
module.exports = {
preset: "jest-expo",
transform: { "\\.mjs$": expoPreset.transform["\\.[jt]sx?$"] },
transformIgnorePatterns: [
"/node_modules/(?!(.pnpm|react-native|@react-native|@react-native-community|expo|@expo|@expo-google-fonts|react-navigation|@react-navigation|@sentry/react-native|native-base|standard-navigation|@configdirector|@noble))",
"/node_modules/react-native-reanimated/plugin/",
"/node_modules/@react-native/babel-preset/",
],
};
These transformIgnorePatterns are the ones jest-expo 57 sets, with @configdirector and @noble added. For another version of jest-expo, start from the transformIgnorePatterns in its jest-expo/jest-preset and add the same two packages. For an app without Expo:
module.exports = {
preset: "@react-native/jest-preset",
transform: { "\\.mjs$": "babel-jest" },
transformIgnorePatterns: ["node_modules/(?!((jest-)?react-native|@react-native(-community)?|@configdirector|@noble)/)"],
};
Under either preset, AppState.addEventListener is a mock that never calls its listener, so the provider never pauses on its own. A test that calls the registered listener to simulate backgrounding runs the provider's production pause and resume against the test client, where a resume always delivers the stored values at once.
Test client controls
values, setValue, removeValue, and replaceValues take native values, and the config type follows from each value: a boolean, an integral number (integer), any other number (float), a string, or a plain object or array (json). holdInitialization, completeInitialization, and failInitialization drive initialize, so loading and error states can be tested, and holdContextUpdate, completeContextUpdate, and failContextUpdate do the same for updateContext. contextUpdates records the context of every initialize and updateContext call, and trackedEvents the events the code under test tracked with track. The JavaScript SDK's testing section describes every control and what to expect from the client.