React SDK reference
Read time: 5 minutes
Last edited: Feb 03, 2021
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.
This reference guide documents all of the methods available in our client-side React SDK, and explains in detail how these methods work. If you want to dig even deeper, our SDKs are open source — head to the React SDK code in our JavaScript SDK GitHub repository. The online API docs contain the programmatic definitions of every type and method. You can also clone and run a sample application using this SDK.
If you want to use LaunchDarkly in a Gatsby application, we have a Gatsby plugin.
The React SDK builds on top of 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.
This SDK uses the Context API, which requires React version 16.3.0 or later. You must use a newer version if you wish to use the Hooks API as well. To learn more, read Hooks.
Getting started
Building on top of our Getting Started guide, the following steps will get you started with using the LaunchDarkly SDK in your React code.
You can use either npm
or yarn
to install the React SDK:
1npm i --save launchdarkly-react-client-sdk
After you install the dependency, initialize the React SDK. To do this, you need your environment's client-side ID, which is available in LaunchDarkly's Account Settings page. Client-side IDs are not secret. You can expose them in your client-side code with no risk.
You can initialize the React SDK in two ways. The first is using the asyncWithLDProvider
function. The second is using the withLDProvider
function.
Both rely on React's Context
API to make it easy for you to access your flags from any level of your component hierarchy. Both functions accept a ProviderConfig
object used to configure the React SDK. For more information about these functions, continue reading.
asyncWithLDProvider
The asyncWithLDProvider
function initializes the React SDK and returns a provider which is a React component. It is an async function.
1import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk';23(async () => {4 const LDProvider = await asyncWithLDProvider({5 clientSideID: 'your-client-side-id',6 user: {7 "key": "aa0ceb",8 "name": "Grace Hopper",9 "email": "gracehopper@example.com"10 },11 options: { /* ... */ }12 });1314 render(15 <LDProvider>16 <YourApp />17 </LDProvider>,18 document.getElementById('reactDiv'),19 );20})();
After initialization is complete, your flags and the ldClient become available at the start of your React app lifecycle. This ensures your app does not flicker due to flag changes at startup time.
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.
The asyncWithLDProvider
function uses the Hooks API, which requires React version 16.8.0 or later.
withLDProvider
The withLDProvider
function initializes the React SDK and wraps your root component in a Context.Provider
:
1import { withLDProvider } from 'launchdarkly-react-client-sdk';23export default withLDProvider({4 clientSideID: 'your-client-side-id',5 user: {6 "key": "aa0ceb",7 "name": "Grace Hopper",8 "email": "gracehopper@example.com"9 },10 options: { /* ... */ }11})(YourApp);
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 JavaScript SDK reference.
Consequently, in the React SDK, streaming mode is enabled by default. To disable streaming mode, specify a streaming: false
attribute in your options
object.
withLDConsumer
The return value of withLDConsumer
is a wrapper function that takes your component and returns a React component injected with flags
& ldClient
as props.
1import { withLDConsumer } from 'launchdarkly-react-client-sdk';23const Home = ({ flags, ldClient /*, ...otherProps */ }) => {4 // You can call any of the methods from the JavaScript SDK5 // ldClient.identify({...})67 return flags.devTestFlag ? <div>Flag on</div> : <div>Flag off</div>;8};910export default withLDConsumer()(Home);
Configuring the React SDK
The ProviderConfig
object configures the React SDK. The only mandatory property is the client-side ID. All other properties are optional.
clientSideID
: This is your project and environment specific client-side ID. This property is mandatory.user
: A LaunchDarkly user object. This property is optional.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 theuser
property is defined.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. As mentioned above, if indicated that the SDK should bootstrap flags from local storage, this will not happen until the SDK initializes.
flags
: If specified, the React SDK will only subscribe for updates to these flags. When this property is unspecified, 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 JS SDKvariation
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:
1{2 clientSideID: "your-client-side-id",3 user: {4 key: "aa0ceb",5 name: "Grace Hopper",6 email: "gracehopper@example.com"7 },8 options: {9 bootstrap: "localStorage"10 },11 reactOptions: {12 useCamelCaseFlagKeys: false13 },14 deferInitialization: false,15 flags: {16 "my-bool-flag": true,17 "my-int-flag": 518 }19}
Hooks
The React SDK offers two custom hooks which you can use as an alternative to withLDConsumer
: useFlags
and useLDClient
.
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.
1import React from 'react';2import { useFlags, useLDClient } from 'launchdarkly-react-client-sdk';34const HooksDemo = () => {5 const { devTestFlag } = useFlags();6 const ldClient = useLDClient();78 const onLoginSuccessful = () => ldClient.identify({ key: 'aa0ceb' });910 return (11 <div>{devTestFlag ? 'Flag on' : 'Flag off'}</div>12 );13};1415export default HooksDemo;
Users
All user-related functionality provided by the JavaScript SDK is equally accessible in the React SDK. To learn more, read the users, private user attributes, and anonymous users sections of the JavaScript SDK reference guide.
Unlike the JavaScript SDK, the React SDK does not require a user object for initialization. If one is not specified, the React SDK will proceed with an anonymous user by default.
Flag keys
LaunchDarkly primarily identifies feature flags by a key which must only contain 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, keys in this format are slightly inconvenient to access in JavaScript and React as they cannot be accessed with the dot notation. As a result, the React SDK automatically camel-cases all flag keys. A flag with key dev-flag-test
is accessible as flags.devFlagTest
.
Automatically camel-casing flag keys poses some problems, though:
- It is possible to induce a key collision if there are multiple LaunchDarkly flag keys which resolve to the same camel-cased key. For example,
dev-flag-test
anddev.flag.test
would be considered unique keys on LaunchDarkly, but the React SDK would consider them to have the same camel-cased keys. - LaunchDarkly's code references tool expects your source code to reference the exact key, not a camel-cased equivalent, so the tool does not support detecting references of keys that were automatically camel-cased.
- As the camel-casing functionality is implemented in the React SDK instead of in the underlying JavaScript SDK, the underlying
ldClient
object and functionality provided by the JavaScript SDK reflect flag keys in their original format. Only React-specific contexts such as your injected props are camel-cased.
To disable the SDK's automatic camel-casing feature, you can provide asyncWithLDProvider
or withLDProvider
with the reactOptions.useCamelCaseFlagKeys
property as shown in the following example. This is supported in versions 2.13.0 and later of the React SDK.
1export default withLDProvider({2 clientSideID: 'your-client-side-id',3 reactOptions: {4 useCamelCaseFlagKeys: false5 }6})(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
Check the 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 dashboard before running the example.