SDK quick linksLaunchDarkly’s SDKs are open source. In addition to this reference guide, we provide source, API reference documentation, and a sample application:
Similar documentation for React Server Component support is available in React Server Component support.
| Resource | Location |
|---|---|
| SDK API documentation | SDK API docs |
| Supported SDK Versions | React Web SDK |
| GitHub repository | js-core/packages/sdk/react |
| Sample application | React Web |
| Published module | npm |
Get started
After you complete the Get started process, follow these instructions to start using the LaunchDarkly React Web SDK in your React code:- Understand version compatibility
- Install the SDK
- Initialize the client
- Identify the context
- Subscribe to flag changes
- Access flag values
Understand version compatibility
The React Web SDK is based on the JavaScript SDK. The React Web 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 Web SDK to use. For a complete client-side JavaScript SDK reference, read JavaScript SDK reference. The React Web SDK version 4.0 requires React version 18.0.0 or higher. The LaunchDarkly React Web SDK versions 3.0 and higher are compatible with React version 16.3.3 and higher. The LaunchDarkly React Web SDK versions 2.x are compatible with React version 16.3.0 and higher. The LaunchDarkly React Web SDK offers eight custom hooks. If you want to use these, then you must use React version 18.0.0 or higher. To learn more, read Hooks.Install the SDK
Install the React Web SDK usingnpm or yarn.
We recommend making the LaunchDarkly observability plugins available as well. These plugins collect and send observability data to LaunchDarkly, including metrics autogenerated from observability events. This means you can review session replay, error monitoring, logs, and traces from within the LaunchDarkly UI. They require the React Web SDK version 3.7 or later.
Here’s how:
Initialize the client
After you install the dependency, your code must initialize the React Web SDK before it can evaluate flags. To do this, we recommend usingcreateLDReactProvider to create an SDK client provider and useInitializationStatus to determine the appropriate time to evaluate your flags.
createLDReactProvider relies on React’s Context API, which lets you access your flags from any level of your component hierarchy. The React Context API is unrelated to LaunchDarkly contexts.
To initialize the React Web SDK, you need your LaunchDarkly environment’s client-side ID and the context for which you want to evaluate flags. This authorizes your application to connect to a particular environment within LaunchDarkly.
The createLDReactProvider function initializes the React Web SDK and returns a Context Provider, which is a React component.
You must initialize createLDReactProvider at the app entry point, prior to rendering, to ensure that flags and the LaunchDarkly client are ready at the start of your React app lifecycle.
This provider enables the use of the new useInitializationStatus status hook, which you can use to react to initialization status updates. Typically, you would want to wait for the SDK initialization status to be complete before trying to evaluate flags.
Here’s how to initialize using createLDReactProvider:
- You can use
createLDReactProviderWithClientto more easily manage multiple SDK client instances. - You can use
createClientto manage your own client instance without React context.
Identify the context
After initialization is complete, your flags and the client are available at the start of your React app lifecycle. This ensures your app does not flicker due to flag changes at startup time. In the React Web SDK, all SDK clients must be initialized with an initialcontext.
If you do not know which context to initialize the SDK with, then we recommend
initializing the SDK with an anonymous context. You can use the identify
function to change this context at any time.
Here’s how to identify the context after initialization:
useInitializationStatus to wait for the client to finish initializing
before calling identify, so the context change is requested immediately. To learn more, read Identifying and changing contexts.
Subscribe to flag changes
The React Web SDK will subscribe to individual flagchange events when you
use one of the variation hooks or
the variation details hooks. This
will automatically open a streaming connection.
In some cases, streaming may not be necessary. For example, if you reload your entire application on each update, you will get all the flag values again when the client is re-initialized. In this situation, we recommend disabling streaming mode. To disable streaming mode, set streaming: false on the ldOptions you pass to createLDReactProvider. When streaming is disabled, no live updates occur.
In other cases, streaming may be required. Subscribing to streaming is the only way to receive real-time updates. If you determine that streaming is necessary for your application, we recommend explicitly enabling streaming mode by setting streaming: true on ldOptions.
Here’s how to configure streaming explicitly:
Access flag values
After your code has initialized the React Web SDK, your primary means to access flag evaluation values is through our variation hooks. Here’s how:Configuration options
ThecreateLDReactProvider function takes two required parameters: a client-side ID and an initial context. You can optionally specify a third LDReactProviderOptions parameter that lets you further configure your provider.
To learn more, read LDReactProviderOptions.
Hooks
The React Web SDK offers eight custom hooks.Single-flag hooks
There are four single-flag hooks:useBoolVariationuseStringVariationuseNumberVariationuseJsonVariation
Single-flag hooks with full evaluation detail
There are four single-flag hooks that provide full evaluation details:useBoolVariationDetailuseStringVariationDetailuseNumberVariationDetailuseJsonVariationDetail
variationIndex, and evaluation reason, re-rendering only when that specific flag changes.
Use these hooks when you need the evaluation reason but don’t want to subscribe to every flag change.
Here’s how to use them:
Example app
For a working single-page app with React and react-router, use this example app.Events
In v4.0 and later of the React Web SDK, the typed variation hooks and variation detail hooks send an evaluation event each time they evaluate a flag. To disable sending events, set thesendEvents configuration option to false.
Event behavior with the deprecated
useFlags hookThe useFlags hook is deprecated in v4.0. To learn more, read Flag keys and the deprecated useFlags hook.If you are still using useFlags, the following event behavior applies:- In versions 2.27 and later, the SDK sends an evaluation event when your app accesses a flag from the
flagsobject returned byuseFlags, and when you call a variation method on theLDClient. - In versions 2.26 and earlier, you must make variation calls directly to send evaluation events.
reactOptions.sendEventsOnFlagRead is set to true or is not specified. Setting it to false prevents evaluation events from being recorded.Do Not Track and ad blocking software
The React Web SDK respects the Do Not Track header. If an end user has Do Not Track enabled in their browser, the SDK does not send analytics events for flag evaluations or metrics to
In addition, ad blocking software may block analytics events from being sent. This does not impact feature flag evaluations. To learn more about the events SDKs send to LaunchDarkly, read Analytics events.
events.launchdarkly.com. To learn more, read Browser privacy settings block analytic events to LaunchDarkly.Flag keys and the deprecated useFlags hook
The useFlags hook is deprecated in v4.0. We recommend migrating to the typed variation hooks. The information in this section only applies if you are still using useFlags.
LaunchDarkly primarily identifies feature flags by a key which must contain only alphanumeric characters, dots (.), underscores (_), and dashes (-). These keys are used in the SDKs to identify flags, and in LaunchDarkly’s REST API.
However, in JavaScript, accessing keys containing . and - requires the bracket operator. Instead of requiring this, the React Web SDK automatically changes all flag keys to camel case by default when you use useFlags. A flag with key dev-flag-test is accessible as flags.devFlagTest.
Automatically changing flag keys to camel case poses some problems:
- 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-testanddev.flag.testare unique keys in LaunchDarkly, but the React Web SDK changes them to the same camel-case key. - If a flag key contains three or more capital letters in a row, the React Web 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
devQAFlagTesttodevQaFlagTest. If you usedevQAFlagTestwith theuseFlags()hook, the SDK will not find the flag. - 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. However, you can configure an alias to ensure that the code references tool detects the camel-case equivalents. To learn more, read Find flag aliases.
- Because the camel-case functionality is implemented in the React Web SDK instead of in the underlying JavaScript SDK, the underlying
clientobject 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.
useCamelCaseFlagKeys option to false when you initialize the SDK. Like useFlags, this option is deprecated and will be removed in a future major version. The typed variation hooks always use the original flag key, so they are not affected by this option.
Here’s how to disable the automatic camel-case feature:
dev-flag-test flag using bracket notation, for example, flags['dev-flag-test'].
If you keep the automatic camel-case feature enabled 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.
Multi-environment support
The React Web SDK supports multiple LaunchDarkly environments in the same React tree. Each environment gets its own React context, provider, and client. Hooks read from whichever context you pass. Here is an example:identify(), is independent. Call it on each client when the user context changes.
Troubleshooting
This section describes common issues you might encounter when using the React Web SDK and how to resolve them.Network error
If your application logs show the errorLaunchDarklyFlagFetchError: network error, there may be a problem with network connectivity between your SDK and LaunchDarkly.
For steps to resolve this issue, read the LaunchDarkly Knowledge Base article Error “LaunchDarklyFlagFetchError: network error”.
CORS errors in local development
If you see CORS errors in the browser while using the ldcli dev-server, check your SDK configuration. The React Web SDK must use your project key as the credential and all service endpoints must point tohttp://localhost:8765.
If you use a client-side ID instead of the project key, the SDK connects to LaunchDarkly rather than the dev-server. This prevents the SDK from retrieving local flag values and can produce CORS errors.
React Server Component support
As of version 4.0 of the React Web SDK, React Server Components are supported. You can perform flag evaluation in React Server Components. This behavior is available as a lightweight wrapper around a server-side SDK that supports enabling frontend changes. You must initialize a separate server-side SDK to interface with React Server Component features. To learn more about the server-side SDKs that support React Server Components, read React Server Component version compatibility.Quick linksReact Server Component support is available as part of the open source React Web SDK. In addition to this reference guide, we provide React Server Component-specific source, API reference documentation, and a sample application:
| Resource | Location |
|---|---|
| API documentation | API docs |
| GitHub repository | js-core |
| Sample application | hello-react-server |
| Published module | npm |
React Server Component version compatibility
These behaviors work with the following React versions:- React version 19.0.0 or higher
Create a wrapped server-side SDK client
This functionality wraps a server-side SDK and makes flag values available to React Server Components on a per-request basis. Here’s how:show-new-feature boolean flag.
Unique behaviors
Several behaviors are only available as part of React Server Component support.createLDServerSession and useLDServerSession
This creates a per-request evaluation scope by binding a server SDK client to a specific context. The session is cached using React’s cache() API, so each request gets its own isolated instance. This also enables useLDServerSession() to retrieve the session from nested React Server Components.
Here is an example:
createLDServerWrapper
This functions identically to createLDServerSession, but does not cache the session. Use this when you want manual lifecycle control or to avoid React’s cache() API.
This is an advanced behavior. Sessions created with createLDServerWrapper are not retrievable by useLDServerSession(). Instead, you must pass the session through props or module scope yourself.
Here is an example: