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

    EDIT ON GITHUB

    React Web SDK reference

    Read time: 10 minutes
    Last edited: Feb 27, 2023
    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.

    Version 3 of the React Web SDK replaces users with contexts

    A context is a generalized way of referring to the people, services, machines, or other resources that encounter feature flags in your product. Contexts replace another data object in LaunchDarkly: "users."

    Code samples on this page are from the two most recent SDK versions where they differ. To learn more about upgrading, read React Web SDK 2.x to 3.0 migration guide and Best practices for upgrading users to contexts.

    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 applicationReact Web
    Published modulenpm

    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 versions 3.0 and higher are compatible with React version 16.3.3 and higher.

    The LaunchDarkly React SDK versions 2.x are 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.

    The LaunchDarkly React SDK version 3.0.0 uses optional chaining. If you encounter an error related to optional chaining during transpiling, bundling, or running tests, updating to version 3.0.2 should resolve the error.

    Getting started

    After you complete the Getting started process, follow these instructions to start using the LaunchDarkly React 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 under Environments on the Projects tab on the 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

    Initializing the React SDK

    After you install the dependency, your code must initialize the React SDK before it can evaluate flags. You can do this in one of two ways:

    • To render your app only after SDK initialization is complete, use await with asyncWithLDProvider
    • To render your app first, and then initialize the SDK and process flag updates, use withLDProvider

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

    When you use asyncWithLDProvider, it initializes the React SDK and returns a provider which is a React component. If you use the asyncWithLDProvider function with await, the rendering of your React app is delayed until SDK initialization completes. Depending on your network conditions, this may take a couple hundred milliseconds. After initialization is complete, your flags and the LaunchDarkly client become available at the start of your React app lifecycle. This ensures that your app does not flicker due to flag changes at startup time. To learn more, read Initializing using the asyncWithLDProvider function.

    Preventing flicker on page load

    Initializing with asyncWithLDProvider can help prevent a flicker on page load if you are using default flag values. To learn more, read Eliminating flicker when using default flag values.

    When you use withLDProvider, it initializes the underlying JavaScript SDK at componentDidMount. This means your flags and the LaunchDarkly client only become available after your app has mounted. Use this method if you prefer to render your app first, and then process flag updates after rendering is complete. You can also optionally defer initialization further, until after you define a context. Because your app renders before initialization, using withLDProvider can result in a flicker due to flag changes at startup time. To learn more, read Initializing using the withLDProvider function.

    Initializing using asyncWithLDProvider

    The asyncWithLDProvider function initializes the React SDK and returns a Context.Provider, which is a React component. It is an asynchronous function. You must initialize asyncWithLDProvider 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.

    The asyncWithLDProvider function accepts an AsyncProviderConfig object, which provides configuration options for the React SDK. To learn more, read Configuring the React SDK. One of these configuration options is the options field, which lets you customize your client. To learn more, read about Configuration for the JavaScript SDK.

    Here's how to initialize using asyncWithLDProvider:

    import { asyncWithLDProvider } from 'launchdarkly-react-client-sdk';
    (async () => {
    const LDProvider = await asyncWithLDProvider({
    clientSideID: 'client-side-id-123abc',
    context: {
    "kind": "user",
    "key": "user-key-123abc",
    "name": "Sandy Smith",
    "email": "sandy@example.com"
    },
    options: { /* ... */ }
    });
    render(
    <LDProvider>
    <YourApp />
    </LDProvider>,
    document.getElementById('reactDiv'),
    );
    })();
    Omitting the kind creates a user object, not a context

    If you omit the kind attribute when you create a context, then LaunchDarkly will assume the context kind is "user" when evaluating flags. Additionally, the SDK will assume you are working with a user object, rather than a context.

    Overall, this should make your upgrade easier, because your existing code will continue to work, as long as you don't make changes to your flag configuration or bucket users based on the "secondary" attribute.

    However, if you are using version 3.0 of the SDK and you are omitting the kind attribute, then the following caveats apply:

    • The fields in your user object must be LDUser fields, not LDContext fields. For example, to mark an attribute as private, you must use privateAttributeNames in the user object, not _meta.privateAttributes as you would for a context object. To learn more, read Understanding changes to private attributes.
    • Any additional attributes in your user object need to be inside the custom property of the LDUser, not at the top-level as they would in a context object. To learn more, read Working with built-in and custom attributes.

    We strongly recommend upgrading your SDK to take advantage of the context functionality.

    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.

    If your app does not yet have the context when you call asyncWithLDProvider, you can omit the context option. This instantiates the client without explicitly specifying a context. Instead, the React SDK uses an anonymous context. Later, when you have the context, you can call identify.

    Here's how to identify the context 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: 'context-key-123abc' });
    }, []);
    return <div>Let your feature flags fly!</div>
    }

    To learn more, read Identifying and changing contexts.

    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, which is a React component.

    The withLDProvider function accepts a ProviderConfig object, which provides configuration properties for the React SDK. In the example below, the context property is specified. Alternatively, you could set the deferInitialization property, and defer initialization until after you define the context property. To learn more, read Configuring the React SDK. Another of these configuration properties is the options field, which lets you customize your client. To learn more, read about Configuration for the JavaScript SDK.

    Here's how to initialize using withLDProvider:

    import { render } from 'react-dom';
    import { withLDProvider } from 'launchdarkly-react-client-sdk';
    import App from './App';
    const LDProvider = withLDProvider({
    clientSideID: 'client-side-id-123abc',
    context: {
    "kind": "user",
    "key": "user-key-123abc",
    "name": "Sandy Smith",
    "email": "sandy@example.com"
    },
    options: { /* ... */ }
    })(App);
    const rootElement = document.getElementById("root");
    render(<LDProvider />, rootElement);

    After initialization is complete, your flags and the client are only available after your app has mounted. Use this method if you prefer to render your app first, and then process flag updates after rendering is complete.

    Subscribing to flag changes

    The React SDK automatically subscribes to flag change events after your app has mounted, which opens a streaming connection. We recommend explicitly enabling streaming mode. To enable streaming mode, specify a streaming: true attribute in your options object. When streaming is disabled, no live updates occur.

    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 context 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.

    This behavior is different from the JavaScript SDK, where you need to opt in to event listening. To learn more about how the JavaScript SDK handles flag change events, read Subscribing to flag changes.

    Using withLDConsumer

    After your code has initialized the React SDK, use withLDConsumer to access flag values and the LaunchDarkly client. 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 specifies configuration for the asyncWithLDProvider function and the ProviderConfig object specifies configuration for the withLDProvider function.

    The only 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 start of your React app lifecycle.

    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.

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

    • options: The 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, or to disable evaluation events on read. This property is optional.

    • deferInitialization: This property allows you to defer SDK initialization until you define the context property. This property is optional, and is only available in ProviderConfig, when you initialize using withLDProvider.

      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.

      However, even if you defer SDK initialization, the SDK continues to load bootstrapped flag values as long as you provide the bootstrapped values 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: A map of flag keys and default values. If you specify this property, the React SDK will only subscribe to updates to these flags. If you do not 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. The React SDK passes each flag's value to the underlying variation call as the default value to use in case of an error. To learn more, read Evaluating flags for the JavaScript SDK.

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

    {
    clientSideID: "client-side-id-123abc",
    context: {
    kind: "user",
    key: "user-key-123abc",
    name: "Sandy Smith",
    email: "sandy@example.com"
    },
    options: {
    bootstrap: "localStorage"
    },
    reactOptions: {
    useCamelCaseFlagKeys: false
    },
    deferInitialization: false,
    flags: {
    "bool-flag-key-123abc": true,
    "numeric-flag-key-123abc": 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

    Both 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 the client and your flags.

    useLDClient is a 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 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 SDK automatically changes all flag keys to camel case by default. 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-test and dev.flag.test are unique keys in LaunchDarkly, but the React SDK changes them to the same camel-case key.
    • If a flag key contains three or more capital letters in a row, the React SDK automatically converts all letters between the first and last capital letter to lower case. For example, the React SDK converts a flag with the key devQAFlagTest to devQaFlagTest. If you use devQAFlagTest with the useFlags() hook, the React 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 Finding flag aliases.
    • 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 React SDK's automatic camel-case feature, provide asyncWithLDProvider or withLDProvider with the reactOptions.useCamelCaseFlagKeys property. The React SDK supports this in versions 2.13.0 and later.

    Here's how to configure the automatic camel-case feature:

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

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

    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.

    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.

    Events

    The React SDK (version 2.27 and later) sends flag evaluation events only when a context receives a flag evaluation, not when allFlags is called. The React SDK calls the JavaScript SDK's allFlags method on load to cache flag values. It uses the JavaScript SDK's sendEventsOnlyForVariation option, set to true, to prevent allFlags from sending evaluation events for every flag.

    Versions 2.26 and earlier of the React SDK send an evaluation event when a user reads a flag evaluation using allFlags and variation. To recreate this behavior in version 2.27 and later, explicitly set options.sendEventsOnlyForVariation: false and set reactOptions.sendEventsOnFlagRead: false. Version 3 only sends events when a context receives a flag evaluation.

    Experimentation events

    Setting reactOptions.sendEventsOnFlagRead: false could prevent experimentation events from recording correctly. Always confirm that this option is disabled when troubleshooting experiments.

    To learn more about the sendEventsOnlyForVariation option, read the JavaScript SDK API documentation. To learn more about the sendEventsOnFlagRead option, read the React SDK API documentation.