• Home
  • Integrations
  • SDKs
  • Guides
  • API docs
No results for ""
EXPAND ALL

EDIT ON GITHUB

React Web SDK reference

Read time: 6 minutes
Last edited: Jul 29, 2022
The React SDK does not work in React Native projects

If you want to add LaunchDarkly to your React Native codebase, use the React Native SDK instead. The React SDK is intended for use in web applications, and the React Native SDK is specifically designed to run in mobile environments. To learn more, read React Native SDK.

Overview

This topic documents how to get started with the client-side React SDK, and links to reference information on all of the supported features.

SDK quick links

LaunchDarkly's SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:

ResourceLocation
SDK API documentationSDK API docs
GitHub repositoryreact-client-sdk
Sample applicationexample
Published modulenpm

You can use LaunchDarkly in a Gatsby application with our Gatsby plugin.

The sample code snippets for this SDK are in JavaScript. To learn more about using TypeScript with the React SDK, read Importing types and Using LaunchDarkly with TypeScript.

The React SDK is based on the JavaScript SDK

The React SDK builds on LaunchDarkly's JavaScript SDK to provide a better integration for use in React applications. As a result, much of the JavaScript SDK functionality is also available for the React SDK to use. For a complete client-side JavaScript SDK reference, read JavaScript SDK reference.

SDK version compatibility

The LaunchDarkly React SDK is compatible with React version 16.3.0 and higher.

The LaunchDarkly React SDK offers two custom hooks. If you want to use these, then you must use React version 16.8.0 or higher. To learn more, read Hooks.

Getting started

After you complete the Getting started process, follow these instructions to start using the LaunchDarkly SDK in your React code.

To install the React SDK, you need your LaunchDarkly environment's client-side ID. Your client-side ID is available in the Environments tab of your project under Account settings page.

Never embed a server-side SDK key into a client-side application

Client-side IDs are not secret and you can expose them in your client-side code without risk. However, never embed a server-side SDK key into a client-side application.

Install the React SDK using either npm or yarn:

npm install launchdarkly-react-client-sdk

After you install the dependency, initialize the React SDK. You can do this in one of two ways:

  • Using the asyncWithLDProvider function
  • Using the withLDProvider function

Both rely on React's Context API which lets you access your flags from any level of your component hierarchy.

Making feature flags available to this SDK

You must make feature flags available to client-side SDKs before the SDK can evaluate those flags. If an SDK tries to evaluate a feature flag that is not available, the user will receive the default value for that flag.

To make a flag available to this SDK, check the SDKs using Client-side ID checkbox during flag creation, or on the flag's Settings tab. To make all of a project's flags available to this SDK by default, check the SDKs using Client-side ID checkbox in your project Settings.

Initializing using asyncWithLDProvider

The asyncWithLDProvider function initializes the React SDK and returns a provider which is a React component. It is an async function. It accepts an AsyncProviderConfig object which is a subset of the ProviderConfig object.

The difference between AsyncProviderConfig and ProviderConfig is that AsyncProviderConfig does not have the deferInitialization property, because asyncWithLDProvider cannot be deferred. You must initialize asyncWithLDProvider at the app entry point prior to rendering to ensure flags and the client are ready at the beginning of the app.

Here's how to initialize asyncWithLDProvider:

import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk';
(async () => {
const LDProvider = await asyncWithLDProvider({
clientSideID: 'your-client-side-id',
user: {
"key": "aa0ceb",
"name": "Grace Hopper",
"email": "gracehopper@example.com"
},
options: { /* ... */ }
});
render(
<LDProvider>
<YourApp />
</LDProvider>,
document.getElementById('reactDiv'),
);
})();

After initialization is complete, your flags and the client become available at the start of your React app lifecycle. This ensures your app does not flicker due to flag changes at startup time.

If your app does not yet have the user context when you call asyncWithLDProvider(), you can instantiate the LDClient and call identify() after initialization is complete.

Here's how to identify the user after initialization:

// app.js
import React, { useEffect } from 'react';
import { useFlags, useLDClient } from 'launchdarkly-react-client-sdk';
export default function App {
const flags = useFlags();
const ldClient = useLDClient();
useEffect(() => {
ldClient.identify({ key: 'enter-user-key' });
}, []);
return <div>Let your feature flags fly!</div>
}

To learn more, read Identifying and changing users.

Rendering may be delayed

Because the asyncWithLDProvider function is asynchronous, the rendering of your React app is delayed until initialization is completed. This can take up to 200 milliseconds, but often completes sooner. Alternatively, you can use the withLDProvider function if you prefer to render your app first and then process flag updates after rendering is complete.

This function requires React 16.8.0 or later

The asyncWithLDProvider function uses the Hooks API, which requires React version 16.8.0 or later.

Initializing using withLDProvider

The withLDProvider function initializes the React SDK and wraps your root component in a Context.Provider. It accepts a ProviderConfig object used to configure the React SDK.

Here's how:

import { render } from 'react-dom';
import { withLDProvider } from 'launchdarkly-react-client-sdk';
import App from './App';
const LDProvider = withLDProvider({
clientSideID: 'your-client-side-id',
user: {
"key": "aa0ceb",
"name": "Grace Hopper",
"email": "gracehopper@example.com"
},
options: { /* ... */ }
})(App);
const rootElement = document.getElementById("root");
render(<LDProvider />, rootElement);

Customize your client from the options field. To learn more, read the JavaScript SDK reference.

The React SDK automatically subscribes to flag change events. This is different from the JavaScript SDK, where customers need to opt in to event listening. To learn more, read Subscribing to flag changes.

In the React SDK, streaming mode is enabled by default. To disable streaming mode, specify a streaming: false attribute in your options object.

Using withLDConsumer

The return value of withLDConsumer is a wrapper function that takes your component and returns a React component injected with flags and ldClient as props.

Here's how:

import { withLDConsumer } from 'launchdarkly-react-client-sdk';
const Home = ({ flags, ldClient /*, ...otherProps */ }) => {
// You can call any of the methods from the JavaScript SDK
// ldClient.identify({...})
return flags.devTestFlag ? <div>Flag on</div> : <div>Flag off</div>;
};
export default withLDConsumer()(Home);

Configuring the React SDK

The AsyncProviderConfig object provides configuration to the asyncWithLDProvider function and the ProviderConfig object provides configuration to the withLDProvider function.

The only mandatory property is the client-side ID. All other properties are optional.

These are the properties:

  • clientSideID: This is your project and environment specific client-side ID. This property is mandatory.

  • user: A LaunchDarkly user object. This property is optional unless you are initializing in secure mode, in which case it is mandatory.

  • options: LaunchDarkly JavaScript SDK initialization options. This property is optional.

  • reactOptions: This property is specific to the React SDK. You can use this option to disable automatic camel casing of flag keys when using the React SDK. This property is optional.

  • deferInitialization: This property allows SDK initialization to be deferred until you define the user property.

    asyncWithLDProvider does not support deferInitialization. You must initialize asyncWithLDProvider at the app entry point prior to rendering to ensure flags and the client are ready at the beginning of your app.

    By deferring SDK initialization, you defer all steps which take place as part of SDK initialization, including reading flag values from local storage and sending the SDK's ready event.

    The one exception to this rule is that the SDK continues to load bootstrapped flag values as long as the bootstrapped values are provided as a map of flag keys and values. If you indicate that the SDK should bootstrap flags from local storage, this will not happen until the SDK initializes.

  • flags: If you specify this, the React SDK will only subscribe for updates to these flags. When you don't specify this property, the React SDK subscribes to all flags. This property is optional.

    Specify the flags property as a map of flag keys and values. The flag keys must be in their original form as known to LaunchDarkly rather than in their camel-cased form. Each flag's value is passed along to the resulting JavaScript SDK variation invocation and used as the flag's default value in the case of an error.

The following is an example ProviderConfig object including each of the above properties:

{
clientSideID: "your-client-side-id",
user: {
key: "aa0ceb",
name: "Grace Hopper",
email: "gracehopper@example.com"
},
options: {
bootstrap: "localStorage"
},
reactOptions: {
useCamelCaseFlagKeys: false
},
deferInitialization: false,
flags: {
"my-bool-flag": true,
"my-int-flag": 5
}
}

Hooks

The React SDK offers two custom hooks which you can use as an alternative to withLDConsumer: useFlags and useLDClient.

These functions require React 16.8.0 or later

useFlags and useLDClient use the Hooks API, which requires React version 16.8.0 or later.

useFlags is a custom hook which returns all feature flags. It uses the useContext primitive to access the LaunchDarkly context set up by asyncWithLDProvider or withLDProvider. You still must use the asyncWithLDProvider or the withLDProvider higher-order component at the root of your application to initialize the React SDK and populate the context with LDClient and your flags.

useLDClient is the second custom hook which returns the underlying LaunchDarkly JavaScript SDK client object. Like the useFlags custom hook, useLDClient also uses the useContext primitive to access the LaunchDarkly context set up by asyncWithLDProvider or withLDProvider. You still must use the asyncWithLDProvider or the withLDProvider higher-order component to initialize the React SDK to use this custom hook.

For an example of how to use a custom hook, read HooksDemo.

Flag keys

LaunchDarkly primarily identifies feature flags by a key which must contain only alphanumeric characters, dots (.), underscores (_), and dashes (-). These keys are used across all of LaunchDarkly's APIs as well as in the SDKs to identify flags.

However, JavaScript and React cannot access keys with a dot notation, so the React SDK automatically changes all flag keys to camel case. A flag with key dev-flag-test is accessible as flags.devFlagTest.

Automatically changing flag keys to camel case poses some problems:

  1. It is possible to induce a key collision if there are multiple LaunchDarkly flag keys which resolve to the same camel-case key. For example, dev-flag-test and dev.flag.test are unique keys in LaunchDarkly, but the React SDK changes them to the same camel-case key.
  2. If a flag key contains three or more capital letters in a row, the SDK automatically converts all letters between the first and last capital letter to lower case. For example, the SDK converts a flag with the key devQAFlagTest to devQaFlagTest. If you use devQAFlagTest with the useFlags() hook, the SDK does not find the flag.
  3. LaunchDarkly's code references tool expects your source code to reference the exact key, not a camel-case equivalent. The tool does not detect keys that were automatically changed to camel-case.
  4. Because the camel-case functionality is implemented in the React SDK instead of in the underlying JavaScript SDK, the underlying client object and functionality provided by the JavaScript SDK reflect flag keys in their original format. Only React-specific contexts such as your injected props use camel case.

To disable the SDK's automatic camel-case feature, provide asyncWithLDProvider or withLDProvider with the reactOptions.useCamelCaseFlagKeys property as shown in the following example. The SDK supports this in versions 2.13.0 and later of the React SDK.

If you enable the automatic camel-case feature and you want to use LaunchDarkly's code references tool, you can configure alias support to find camel-cased flags. To do so, use the value camelCase for the alias settings.

Here's how to configure alias:

export default withLDProvider({
clientSideID: 'your-client-side-id',
reactOptions: {
useCamelCaseFlagKeys: false
}
})(App);

With this configuration option in place, you would now access your dev-flag-test flag using bracket notation. For example, flag['dev-flag-test'].

Example app

Run this example for a fully working single page app with React and react-router. You must enter your clientSideId in the client root app file and create a flag with key dev-test-flag in your flags list before running the example.

Importing types

In addition to its own bundled types, the React SDK uses types from launchdarkly-js-client-sdk. If you use Typescript and you need to use launchdarkly-js-client-sdk types, you can install the launchdarkly-js-client-sdk package as a dev dependency. You can then import the types you want directly from launchdarkly-js-client-sdk.

If you are using the React SDK within a React application that uses TypeScript, you may encounter some compiler errors or warnings initially. One solution is to wrap your component in a withLDProvider function, and then coerce your component to type <ComponentType<{}>. To learn how, read Using LaunchDarkly with TypeScript.

If you use eslint, the SDK requires that you add launchdarkly-js-client-sdk as a dev dependency. Otherwise, eslint will report a no-extraneous-dependencies error.